CALayer not rendering contents

2019-07-30 11:29发布

问题:

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:

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.