用可可绘制线分隔符

时间:2013-02-25 15:44:41

标签: objective-c cocoa nsview nsbox

如何绘制这样的行分隔符:

enter image description here

请注意,彼此顶部有2条单像素线。有什么提示吗?


编辑:

这是我需要的代码,在NSBox子类中:(或NSView,并不重要):

- (void)drawRect:(NSRect)rect
{
    [[NSColor lightGrayColor] set];
    NSRectFill(NSMakeRect(0, 1, NSWidth(rect), 1));

    [[NSColor whiteColor] set];
    NSRectFill(NSMakeRect(0, 0, NSWidth(rect), 1));    
}

3 个答案:

答案 0 :(得分:7)

通常,这种分隔符使用NSBox绘制,通常配置为NSBoxSeparator类型。但这并不是你想要的外观。我建议在NSBox子类中手绘它(这样你就可以获得正常的NSBox行为)。有关NSBox子类的示例,请参阅Matt Gemmell的RoundedBox

你只需要两行,所以drawRect:应该非常简单。以这种方式封装将使您非常灵活。

(当然你也可以考虑使用标准NSBox分隔符,而不是创建自定义外观。这就是它的用途。)

答案 1 :(得分:1)

我使用iOS模仿这样的东西,假设NSView有类似的界面,我希望这会有所帮助:

UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(11, 99, 298, 1)];
lineView.backgroundColor = [UIColor darkGrayColor];
[panel addSubview:lineView];

UIView *lineView2 = [[UIView alloc] initWithFrame:CGRectMake(10, 100, 300, 1)];
lineView2.backgroundColor = [UIColor whiteColor];
[panel addSubview:lineView2];

自己看一下NSView界面,它似乎几乎可以直接转移:

NSView *lineView = [[NSView alloc] initWithFrame:CGRectMake(11, 99, 298, 1)];
lineView.backgroundColor = [NSColor colorWithCalibratedRed:0.4f green:0.4f blue:0.4f alpha:1.0f];
[panel addSubview:lineView];

NSView *lineView2 = [[NSView alloc] initWithFrame:CGRectMake(10, 100, 300, 1)];
lineView2.backgroundColor = [NSColor colorWithCalibratedRed:1.0f green:1.0f blue:1.0f alpha:1.0f];
[panel addSubview:lineView2];

答案 2 :(得分:0)

你也可以使用CALayer

CALayer *lineLayer = [CALayer layer];
lineLayer.frame = (CGRectMake(0, 100, 300, 1));
[lineLayer setBackgroundColor:CGColorCreateGenericRGB(1.0, 1.0, 1.0, 1.0)];
[panel.layer addSublayer: lineLayer];

或(如果您无权访问图层)

CALayer *lineLayer = [CALayer layer];
lineLayer.frame = (CGRectMake(0, 100, 300, 1));
[lineLayer setBackgroundColor:CGColorCreateGenericRGB(1.0, 1.0, 1.0, 1.0)];
[panel setWantsLayer:YES];
[panel setLayer: lineLayer];