I am working on a Mac app and need a custom NSView with 4 rounded corners. Everything I have tried either produces no results, or only curves the botton two edges of the NSView
. Is there a way to curve all 4 corners of an NSView
?
I tried making a custom class and used the initWithFrame
method which produces no results what so ever. I then tried the drawRect
method which curves the bottom two corners only:
-(void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
[self setWantsLayer:YES];
[self.layer setFrame:self.frame];
[self.layer setMasksToBounds:YES];
[self.layer setCornerRadius:10.0f];
}
How can I curve all four corners? And does anyone know why developing for the Mac is so much harder than on iOS. Why does even the most basic task always require a custom class (i.e.: setting the NSView background colour or running the equivalent of a UIViewAnimation
....).
This three lines give me rounded corners and red background for the testView
of type NSView
linked as an outlet from storyboard in viewDidLoad
of a ViewController, no subclassing needed:
_testView.wantsLayer = YES;
_testView.layer.backgroundColor = [NSColor redColor].CGColor;
_testView.layer.cornerRadius = 10.;
Edit
Not all corners were rounded because of this line:
[self.layer setFrame:self.frame];
Basically you don't need it, you set proper layer frame with this line:
[self setWantsLayer:YES];
If you do want to set layer frame explicitely, you want to use
[self.layer setFrame:self.bounds];
Read about difference between frame
and bounds
.
And aforementioned code works in drawRect:
too.