0

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.

Community
  • 1
  • 1
Anna Fortuna
  • 1,071
  • 2
  • 17
  • 33

1 Answers1

2

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.

David H
  • 40,852
  • 12
  • 92
  • 138
  • So if I am using the UIView's layer instead of the custom layer, and I decided to override the `+ (Class)layerClass` to implement the custom layer, does this mean that I can no longer use the `drawLayer:inContext:` method of the UIView's layer anymore? – Anna Fortuna Jul 18 '12 at 01:14
  • Not at all. By using this technique, you can get the UIView subclass to your the CALayer subclass of your choosing (i.e., a CATiledlayer, or your own CALayer subclass). Since it is a subclass, it will implement all the CALayer functionality, plus some additional methods that you might want to add (as you stated above). – David H Jul 18 '12 at 14:00