Rounded rect on NSView that clips all containing subviews

ε祈祈猫儿з 提交于 2019-12-20 17:41:12

问题


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:

How can I achieve this?


回答1:


Have you tried clipping with layers?

self.layer.cornerRadius = self.radius; self.layer.masksToBounds = YES;


Ah, sorry, somehow I've missed that you were talking about NSView, not UIView. It would be hard to clip NSView subviews in all cases because it seems that most of Cocoa standard views set their own clipping path. It might be easier to layout subviews with some paddings and avoid need for clipping.




回答2:


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;
}



回答3:


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



来源:https://stackoverflow.com/questions/5087542/rounded-rect-on-nsview-that-clips-all-containing-subviews

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!