简体   繁体   中英

How to identify CAShapeLayer within the animationDidStop

I have an array of CAShapeLayer . At some point I must iterate through that array and start an animation for each layer. Those animations change the bounds.size.height of the layers to different values (computed in some way). In the animationDidStop method I'd like to actually change the height of each layer to the animation.toValue value. I need to do this because I want the future animations to start from the new values and not from the initial values. This is the loop:

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"];
}

In the animationDidStop method I'd like to do something like this (equivalent to this, actually; the if-else paradigm is not the best):

-(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;

        */
    }
}

Any idea? Thank you.

Give a specific value for each animation you set to each CAShapeLayer as you loop through your layers array, like so:

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

In your 'animationDidStop' method, check the value of the animation parameter for the value, like so:

-(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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM