Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounded rect on NSView that clips all containing subviews

I am creating a NSView subclass that has rounded corners. This view is meant to be a container and other subviews will be added to it. I am trying to get the rounded corners of the NSView to clip all of the subview's corners as well, but am not able to get it.

- (void)drawRect:(NSRect)dirtyRect {
    NSRect rect = [self bounds];
    NSBezierPath *path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:self.radius yRadius:self.radius];
    [path addClip];

    [[NSColor redColor] set];
    NSRectFill(dirtyRect);

    [super drawRect:dirtyRect];     
}

The red is just for example. If I add a subview to the rect, The corners are not clipped: enter image description here

How can I achieve this?

like image 596
coneybeare Avatar asked Feb 23 '11 06:02

coneybeare


2 Answers

Using Core Animation layers will clip sublayers correctly.

In your container NSView subclass:

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.layer = _layer;   // strangely necessary
        self.wantsLayer = YES;
        self.layer.masksToBounds = YES;    
        self.layer.cornerRadius = 10.0;    
    }    
    return self;
}
like image 76
Jason Harwig Avatar answered Sep 19 '22 05:09

Jason Harwig


You can do it in the interface builder without subclassing adding User Defined Runtime Attributes"

enter image description here

like image 41
Tibidabo Avatar answered Sep 20 '22 05:09

Tibidabo