Search code examples
ioscore-animationcalayer

make custom CALayer subclass automatically redraw itself after being added to a super layer


I am subclassing CALayer and doing custom drawing in drawInContext: method.

The problem is I need to manually call setNeedsDisplay: after I add an instance of my subclass to a superlayer, something like:

MyCustomLayer *instance = [MyCustomLayer layer];
//do some configurations
[self.view.layer addSublayer:instance];
[layer setNeedsDisplay]; //required

or the drawing will not happen.

But when I use buit-in CALayer subclasses (CATextLayer, CAShapeLayer etc.), the call to setNeedsDisplay: is not needed after adding them to a super layer. Can I make my subclass behaves like those classes?


Solution

  • You can call displayIfNeeded on yourself within the init method, however better is to subclass needsDisplayForKey: and return YES for the @"transform" key, which would redraw when the bounds changes (i.e. when first added to the view).