1
votes

This one is stumping me. I have a CALayer which I create in a UIViewController's viewDidLoad method something like this:

- (void)viewDidLoad {

    [super viewDidLoad];

    UIImage* img = [UIImage imageNamed:@"foo.png"];

    _imageLayer = [[CALayer alloc] init];

    _imageLayer.bounds = CGRectMake( 0, 0, img.size.width, img.size.height);
    _imageLayer.position = CGPointMake( self.view.bounds.size.width/2.0, self.view.bounds.size.height/2.0 );

    _imageLayer.contents = (id)img.CGImage;
    _imageLayer.contentsScale = img.scale;

    [self.view.layer addSublayer:_imageLayer];
    [_imageLayer setNeedsDisplay];
}

The UIViewController is loaded from a nib and placed into a UITabBarController that was created in code.

My problem is that the CALayer does not render its UIImage contents when the UIViewController becomes visible. The only way I can make the CALayer to render the UIImage is by setting its contents to the UIImage after the UIViewController is made visible, such as in the viewDidAppear: method.

I would really prefer to do all my set up in the viewDidLoad method (isn't that what's it’s for?). How do I get the CALayer to render its contents?

1
Why are you calling -setNeedsDisplay on the new layer (which was not modified), and not on your view's layer?user529758
Just a simple attempt to get it to render.kamprath
Oh wait, I see your point. If I remove the [_imageLayer setNeedsDisplay];, it works just fine. What is happening there?kamprath
I mean, setNeedsDisplay needs to be called on the superview, not on the subview.user529758

1 Answers

3
votes

You don't need that setNeedsDisplay on the layer, or the superview.

setNeedsDisplay tells a layer or view that it needs to redraw its contents. (For a view, it will call drawRect: to get new contents; for a CALayer, it will ask its delegate.) Note that this affects only the view or layer itself, not its children.

Since you are providing the content for the layer directly, you don't want CA to discard that content and ask for a replacement.