如何在animationDidStop中识别CAShapeLayer

时间:2014-12-22 10:12:14

标签: ios objective-c core-animation calayer cabasicanimation

我有一个CAShapeLayer数组。在某些时候,我必须遍历该数组并为每一层启动动画。这些动画将图层的bounds.size.height更改为不同的值(以某种方式计算)。在animationDidStop方法中,我想将每个图层的高度实际更改为animation.toValue值。我需要这样做,因为我希望未来的动画从新值开始,而不是从初始值开始。这是循环:

for (int i=0; i<[layersArray count]; i++) {
    newLayerHeight = [self computeNewHeightForLayer:[layersArray objectAtIndex:i];

    CABasicAnimation *myAnim = [CABasicAnimation animationWithKeyPath:@"bounds.size.height"];
    myAnim.delegate = self;
    myAnim.duration = 0.4;
    myAnim.removedOnCompletion = NO;
    myAnim.fillMode = kCAFillModeForwards;
    myAnim.fromValue = [NSNumber numberWithFloat:[layersArray objectAtIndex:i]).bounds.size.height];
    myAnim.toValue = [NSNumber numberWithFloat:newLayerHeight];
    [[layersArray objectAtIndex:i] addAnimation:myAnim forKey:@"changeHeightAnim"];
}

animationDidStop方法中,我想做类似这样的事情(实际上等同于if-else范式并不是最好的):

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    if(flag){
        /*
            if(anim is linked to layer0)change the height of layer0;
            if(anim is linked to layer1)change the height of layer1;
            .
            .
            .
            if(anim is linked to layerN-1)change the height of layerN-1;

        */
    }
}

有什么想法吗?谢谢。

1 个答案:

答案 0 :(得分:2)

为循环遍历图层数组时为每个CAShapeLayer设置的每个动画指定一个特定值,如下所示:

[myAnim setValue:@"layer_1" forKey:@"animation_id"];
[myAnim setValue:@"layer_2" forKey:@"animation_id"]; 
...

在'animationDidStop'方法中,检查值的animation参数值,如下所示:

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    if([[anim valueForKey:@"animation_id"] isEqual:@"layer_1"]) {
        // do something
    }
    else if([[anim valueForKey:@"animation_id"] isEqual:@"layer_2"]) {
        // do something
    }
}