small medium large xlarge

17 Aug 2009, 06:40
Darren Minifie (2 posts)

Hi I’m trying to use a CALayer with a custom view to create a rounded view. Try to picture a long horizontal oval with rounded buttons on the left edge. I wanted to use a clipped CALayer for this that has its corner radius set high. The view looks good, but when i try to add the buttons as subviews, they do not get displayed correctly. Here is my code, maybe I’m just having “one of those days” and the mistake is obvious:


-(id)initWithFrame:(NSRect)frame Controller:(NSViewController*)aController{
	self = [super initWithFrame:frame];
	[self setViewController:aController];
	// Set up the view's layer
	[self setLayer:[CALayer layer]];
	[self setWantsLayer:YES];
	[[self layer] setDelegate:self];
	[[self layer] setNeedsDisplay];
	[[self layer] setMasksToBounds:YES];
	// visual attributes of the layer:
	[[self layer] setBorderColor:CGColorCreateGenericRGB(0.8, 0.8, 0.8, 1.0)];
	[[self layer] setBackgroundColor:CGColorCreateGenericRGB(0.3, 0.3, 0.3, 1.0)];
	[[self layer] setBorderWidth:5.0];
	[[self layer] setCornerRadius:50.0];

	// Add the three left buttons
	NSButton* b1 = [[NSButton alloc] initWithFrame:NSMakeRect(0, 0.0, 50.0, 50.0)];
	[b1 setButtonType:NSOnOffButton];
	[b1 setTitle:@"b1"];
	[self addSubview:b1];
	NSButton* b2 = [[NSButton alloc] initWithFrame:NSMakeRect(0.0, 50.0, 50.0, 50.0)];
	[b2 setButtonType:NSOnOffButton];
	[b2 setTitle:@"b2"];
	[self addSubview:b2];
	[b2 setFrame:NSMakeRect(0.0, 50.0, 50.0, 50.0)];
	NSButton* b3 = [[NSButton alloc] initWithFrame:NSMakeRect(0.0, 100.0, 50.0, 50.0)];
	[b3 setButtonType:NSOnOffButton];
	[b3 setTitle:@"b3"];
	[self addSubview:b3];
	return self;


The problem is strange, only the last button is visible, and it’s placed at (0,0), even though I’ve set its frame to be otherwise. Thanks for any help.

PS: awesome book, i’ve read it several times.

17 Aug 2009, 13:53
Bill Dudney (917 posts)

Hi Darren,

Thanks for the kind words!

Strange problem. One thought that came to mind, since you are clipping to the bounds and the corner radius is 50 your layer could be dropping the first 2 buttons out of the picture (because it things they are going to be clipped). Just as a debugging step I’d reduce the corner radius to 2 and see what happens.

Good luck!

You must be logged in to comment