Search code examples
ioscore-animation

How do I have my UIView use my custom CALayer as its backing layer?


I am overriding UIView's layerClass method as recommended in apple's documentation like this:

+ (Class)layerClass {
     return [ViewLayerBase class];
}

In my viewLayerBase custom class I have an init Method implemented like this:

- (id)initWithRect:(CGRect)rect {
     if ((self = [super init])) {
         NSLog(@"I got called");
     }
     return self;
}

This method is clearly not being called by my UIView subclass. Given that the layer property of UIView is read-only and I cannot do myView.layer = [ViewLayerBase alloc] initWithRect... how do I get UIView to instantiate my custom CALayer subclass?


Solution

  • You are doing it right (adding a layerClass class method to your custom UIView class.)

    The problem is your init method. For CALayer, the designated init method is init, not initWithRect. Try moving your code to -init. That should work.