iOS目标C:如何将更多参数传递给animationDidStop?

时间:2015-02-01 09:41:45

标签: objective-c ios8 delegates core-animation

我需要在动画停止后做一些事情,所以我把自己当作代表

CAShapeLayer* myLayer = [CAShapeLayer layer];
...
CABasicAnimation * animation;
...
animation.delegate=self;
...
[myLayer addAnimation:animation];

这只是一个简单的例子来解释这种情况。 像往常一样,这是最后的被调用方法

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag

我需要另一个参数,我不想把它作为类的成员,因为它将被其他方法看到。我需要在创建动画时添加一个整数参数作为委托的另一个方法,以便将其作为本地参数。 例如:

-(void)myAnimationDidStop:(CAAnimation *)anim finished:(BOOL)flag index:(int) ind

有没有办法达到这个目标?

2 个答案:

答案 0 :(得分:2)

您的代理人可以管理每个动画后处理所需的数据。我正在考虑将动画对象作为键的NSMutableDictionary:

// where you setup the animation
animation.delegate=self;
MyAnimationDataClass *myAnimationData;
[self.runningAnimations setObject: myAnimationData forKey: animation];

然后在你的委托方法回调中:

-(void)myAnimationDidStop:(CAAnimation *)anim finished:(BOOL)flag index:(int) ind {
  MyAnimationDataClass *myData = [self.runningAnimations objectForKey: anim];
  if (myData) {
    // do your postprocessing
  }  
}

答案 1 :(得分:1)

您实际上可以为图层和动画对象上的任何键设置值。请注意,由于动画在添加到图层时会被复制,因此您必须在将值添加到图层之前设置该值,否则您将修改另一个对象,然后再修改最终完成的对象。

此行为记录在Core Animation Programming Guide

  

CAAnimation和CALayer类是符合键值编码的容器类,这意味着您可以为任意键设置值。即使键someKey不是CALayer类的声明属性,您仍然可以为它设置一个值,如下所示:

// before adding the animation (because the animation get's copied)
[theAnimation setValue:yourValueHere forKey:@"yourKeyHere"];

然后在animationDidStop中检索它:

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{
    id yourExtraData = [anim valueForKey:@"yourKeyHere"];
    if (yourExtraData) {
        // do something with it
    }
}