Animating a custom property of CALayer subclass

Yes, it’s possible (only in the latest Core Animation releases though, I believe, i.e. iPhone 3.0+ and OS X 10.6+).

  1. Make your property dynamic so that CA implements the accessors for you:

    @dynamic myInt;
    
  2. Tell the layer that changes of the property require redrawing:

    + (BOOL)needsDisplayForKey:(NSString*)key {
        if ([key isEqualToString:@"myInt"]) {
            return YES;
        } else {
            return [super needsDisplayForKey:key];
        }
    }
    
  3. Use the value of myInt in your drawInContext: method. Now, when you animate myInt, Core Animation will interpolate the values for each step of the animation and repeatedly ask the layer to draw itself.

  4. If you also want to enable implicit animations for this property, also override actionForKey:.

Leave a Comment