animationCALayer子类的自定义属性

我有一个CALayer子类MyLayer,它有一个名为myInt的NSInteger属性。 我真的想通过CABasicAnimationanimation这个属性,但似乎CABasicAnimation只适用于所谓的“animation”属性(边界,位置等)。 有什么我可以重写,使我的习惯myInt属性animation?

是的,这是可能的(只有在最新的核心animation发布,但我相信,即iPhone 3.0 +和OS X 10.6 +)。

  1. 使您的资产充满活力,以便CA为您实施访问器:

     @dynamic myInt; 
  2. 告诉图层属性需要重绘的变化:

     + (BOOL)needsDisplayForKey:(NSString*)key { if ([key isEqualToString:@"myInt"]) { return YES; } else { return [super needsDisplayForKey:key]; } } 
  3. drawInContext:方法中使用myInt的值。 现在,当你为myIntanimationmyInt ,Core Animation会插入animation每一步的值,并重复地让图层自己绘制。

  4. 如果您还想为此属性启用隐式animation,还可以覆盖actionForKey:

有一种方法可以保留自定义CALayer子类的iVars。 你重载initWithLayer:,这个方法被调用来创build一个自定义层的副本。 例如,如果您有一个要在其中创build名为“angular度”的自定义属性的图层,则可以使用以下代码:

 @implementation AngledLayer @synthesize angle = _angle // Tell Core Animation that this key should be animated + (BOOL) needsDisplayForKey:(NSString *)key { if ([key isEqualToString:@"angle"]) return YES; return [super needsDisplayForKey:key]; } // Make sure that, when the layer is copied, so is the custom ivar - (id) initWithLayer:(id)layer { self = [super initWithLayer:layer]; if (self) { AngledLayer *angledVersion = (AngledLayer *)layer; self.angle = angledVersion.angle; } return self; } 

而鲍勃是你的叔叔! 请注意,您不能使用此对象的隐式animation,您也必须覆盖actionForKey:方法。