Search code examples
ioscocoa-touchcore-animationcalayer

CALayer not implementing custom drawLayer:inContext: method


I saw this solution while researching for CALayers. I was looking for a way to implement custom drawings inside a UIView with multiple sublayers. I named my sublayers like this:

layer1.name = @"Back";
layer2.name = @"Middle";
layer3.name = @"Front";

And I created custom methods to be implemented by this layers

-(void)drawBackLayer:(CALayer *)layer inContext:(CGContextRef)ctx
-(void)drawMiddleLayer:(CALayer *)layer inContext:(CGContextRef)ctx
-(void)drawFrontLayer:(CALayer *)layer inContext:(CGContextRef)ctx

The problem is these methods are not implemented, instead the drawLayer:inContext:, which is being used by the view's root layer, is implemented four times. This means that the custom layers implement this method instead of the custom methods. Can anyone explain to me why?

NOTE: the solution I am referring in the link is the code provided by Dave Lee.


Solution

  • The layer used by the UIView must be a custom CALayer that implements those messages. The way you get a UIView subclass to use a particular layer is via the class method "+(Class)layerClass".

    So: - subclass a UIView (or subclass of it like UIImageView, etc) - implement the layerClass method, and return [MyCALayer class];

    Now that view will use YOUR CALayer subclass.