Simple example of CALayers in an NSView
I am trying to add several CALayers to an NSView but my view remains empty when shown:
Here is my code:
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.layer = [CALayer layer];
self.wantsLayer = YES;
CALayer *newLayer = [CALayer layer];
NSImage *image = [NSImage imageNamed:@"page.png"];
newLayer.backgroundColor = [NSColor redColor].CGColor;
newLayer.contents = (id)[image CGImageForP开发者_JAVA百科roposedRect:NULL context:NULL hints:nil];
newLayer.frame = NSMakeRect(100,100,100,100);//NSMakeRect(0,0,image.size.width,image.size.height);
newLayer.position = CGPointMake(20,20);
[self.layer addSublayer:newLayer];
}
return self;
}
DO have any idea (or example of code) to perform this task?
Thanks and regards,
The code to set up the layer needs to be in the awakeFromNib method, not in the initWithFrame function.
The explanation why :)
In the nib file your view is marked as not needing a layer, so the flow is
- you set your layers in the initWithFrame: method
- the nib file properties are set up wiping out your layers.
You could also leave your code the way it is, and tell interface builder that your custom view needs a layer.
精彩评论