2011-03-31 39 views
2

我试图在我的NSView的顶部绘制其子视图。 事实上,我试图重现Interface Builder的连接线样式。下面是我使用的那一刻代码:如何在NSView的子视图上绘制

- (void)drawRect:(CGRect)dirtyRect 
{ 
    // Background color 
    [[NSColor whiteColor] setFill]; 
    NSRectFill(dirtyRect); 

    // Draw line 
    if(_connecting) 
    { 
     CGContextRef c = [[NSGraphicsContext currentContext] graphicsPort]; 
     [[NSColor redColor] setStroke]; 

     CGContextMoveToPoint(c, _start.x, _start.y); 
     CGContextAddLineToPoint(c, _end.x, _end.y);   
     CGContextSetLineWidth(c, LINE_WIDTH); 
     CGContextClosePath(c); 
     CGContextStrokePath(c); 
    } 
} 

,第一部分是颜色,我NSView(如果您知道其他的方式,请告诉我,因为我来自iPhone开发想念backgroundColor财产UIView

然后,如果一个连接,如果检测到,我画它与2 NSPoint s。此代码有效,但我没有得到它,只能在第一个NSView上绘制子视图。

回答

9

父视图无法绘制其子视图。你必须在子视图上放置另一个视图并在那里画线。

+0

我以为这个解决方案,但我认为这是一个丑陋的方式。那么,我会这样做。 – klefevre 2011-03-31 12:58:19

+1

如果我需要原始子视图来接收鼠标事件,顶部不被遮挡,绘制子视图会怎么样? – 2012-01-22 15:19:09

+1

您可以重写超级视图上的hitTest,以避免重叠视图。 – 2013-02-05 00:09:45