Search code examples
objective-cmacoscore-animationcalayernsview

adding a sublayer to CALayer works only in mouseDown method


I am trying to add a CALayer to an NSView. The code I have which is not working is

-(void) InsertCALayer
{
    newLayer = [CALayer layer];
    newLayer.frame = NSMakeRect(10, 10, 100, 100);
    newLayer.backgroundColor = CGColorCreateGenericRGB(0.5, 0.5, 0.5, 1.0);
    [rootLayer addSublayer:newLayer];
}

However, nothing shows up with this code. Oddly enough, I have also implemented a mouseDown event handler, and the code does work there:

-(void) mouseDown:(NSEvent *)theEvent
{   
    newLayer = [CALayer layer];
    newLayer.frame = NSMakeRect(10, 10, 100, 100);
    newLayer.backgroundColor = CGColorCreateGenericRGB(0.5, 0.5, 0.5, 1.0);
    [rootLayer addSublayer:newLayer];
}

I can confirm that both methods definitely get called, but I am very confused as to why one works and the other doesn't. Any thoughts?


Solution

  • Is the

    -(void) InsertCALayer
    

    method being called after the view heirarchy has loaded? If you set a breakpoint in the debugger in the InsertCaLayer method and 'po' rootLayer do you have a valid object?

    The view heirarchy must be fully loaded before you make changes to it. I wonder if this is the problem here. Let me know!