如何在NSSplitView中更改分隔符的颜色?

Akk*_*kki 5 cocoa appkit nssplitview xcode4

我们可以改变分频器的颜色吗?Apple文档说,我们可以在NSSplitView的子类中覆盖-dividerColor,但这对我不起作用,或者我的理解不正确.我也尝试在分隔符上创建颜色层,例如:

colorLayer = [CALayer layer];
NSRect dividerFrame = NSMakeRect([[self.subviews objectAtIndex:0] frame].size.width, [[self.subviews objectAtIndex:0] frame].origin.y, [self dividerThickness], self.frame.size.height);

[colorLayer setBackgroundColor:[color coreGraphicsColorWithAlfa:1]];
[colorLayer setFrame:NSRectToCGRect(dividerFrame)];

[self.layer addSublayer:colorLayer];
Run Code Online (Sandbox Code Playgroud)

不行.

Ser*_*gio 8

实际上,简单地进行子类化NSSplitView和重写-(void)dividerColor工作,但仅适用于细分或粗分隔符.

我已经创建了这样的简单可配置拆分视图:

@interface CustomSplitView : NSSplitView
@property NSColor* DividerColor
@end

@implementation CustomSplitView
- (NSColor*)dividerColor {
  return (self.DividerColor == nil) ? [super dividerColor] : self.DividerColor;
}
@end
Run Code Online (Sandbox Code Playgroud)

然后在Interface Builder中为分割视图指定自定义类,CustomSplitView并使用键路径= DividerColor,type = Color添加新的用户定义的运行时属性,并选择所需的分割器颜色.


Pal*_*lle 7

这个答案可能会迟到但是:
如果您使用的是Interface Builder,则可以通过转到NSSplitView(cmd+ alt+ 3)的Identity Inspector 并为dividerColorColor类型添加用户定义的运行时属性来更改属性.


uff*_* da 6

我也尝试了子类化 - (void)dividerColor,我不知道为什么它不起作用,即使我知道它被调用(并且它在文档中).

更改分隔符颜色的一种方法是子类- (void)drawDividerInRect:(NSRect)aRect.但是,出于某种原因,这个方法没有被调用,我已经在网上检查了答案,但找不到任何东西,所以我最终调用了它drawRect.这是子类NSSplitView的代码:

-(void) drawRect {
    id topView = [[self subviews] objectAtIndex:0];
    NSRect topViewFrameRect = [topView frame];
    [self drawDividerInRect:NSMakeRect(topViewFrameRect.origin.x, topViewFrameRect.size.height, topViewFrameRect.size.width, [self dividerThickness] )];
}

-(void) drawDividerInRect:(NSRect)aRect {
    [[NSColor redColor] set];
    NSRectFill(aRect);
}
Run Code Online (Sandbox Code Playgroud)


Ely*_*Ely 5

基于 Palle 的回答,但可以在代码中动态更改颜色,我目前正在使用此解决方案(Swift 4):

splitView.setValue(NSColor.red, forKey: "dividerColor")
Run Code Online (Sandbox Code Playgroud)

如果你的 splitview 控件是 NSSplitViewController 的一部分,你应该使用这样的东西:

splitViewController?.splitView.setValue(NSColor.red, forKey: "dividerColor")
Run Code Online (Sandbox Code Playgroud)

  • @cgiacomi 我刚刚在 macOS 11 上测试了这个,它在我这边仍然有效。确保在加载 splitviewcontroller 后调用 windowDidLoad 中的代码 (2认同)