A simple example of CALayers in NSView

I am trying to add several CALayers to 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 CGImageForProposedRect: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 you have an idea (or sample code) for this task?

Thank you and welcome

+3
source share
1 answer

The code for setting the level should be in the awakeFromNib method, and not in the initWithFrame function.

Explanation of why :)

In the nib file, your view is marked as not needing a layer, so the stream

  • you set your layers in the initWithFrame method:
  • The properties of the nib file are configured to clear your layers.

You can also leave your code as it is and tell the interface developer that your user view requires a layer.

+10
source

Source: https://habr.com/ru/post/1434680/


All Articles