我有一个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;

        */
    }
}


任何想法?谢谢。

最佳答案

在遍历图层数组时,为设置给每个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
    }
}

关于ios - 如何在animationDidStop中识别CAShapeLayer,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27600547/

10-12 14:45