Wednesday, June 12, 2013

CAAnimation animationDidStop example in Objective C (iOS).

CAAnimation animationDidStop

Called when the animation completes its active duration or is removed from the object it is attached to.

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

Parameters of [CAAnimation animationDidStop]
theAnimation
The CAAnimation instance that stopped animating.
flag
If YES, the animation reached the end of its active duration without being removed.

CAAnimation animationDidStop example.
I created a typedef for a block:

typedef void (^animationCompletionBlock)(void);
And a key that I use to add a block to an animation:

#define kAnimationCompletionBlock @"animationCompletionBlock"
Then, if I want to run animation completion code after a CAAnimation finishes, I set myself as the delegate of the animation, and add a block of code to the animation using setValue:forKey:

animationCompletionBlock theBlock = ^void(void)
{
  //Code to execute after the animation completes goes here   
};
[theAnimation setValue: theBlock forKey: kAnimationCompletionBlock];
Then, I implement an animationDidStop:finished: method, that checks for a block at the specified key and executes it if found:

- (void)animationDidStop:(CAAnimation *)theAnimation finished:(BOOL)flag
{
  animationCompletionBlock theBlock = [theAnimation valueForKey: kAnimationCompletionBlock];
  if (theBlock)
    theBlock();
}

Example of [CAAnimation animationDidStop].
You can set key/value objects for CAAnimation instance like this:

CABasicAnimation *theAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
[theAnimation setValue:@"animation1" forKey:@"id"];
theAnimation.delegate = self;

CABasicAnimation *theAnimation2 = [CABasicAnimation animationWithKeyPath:@"opacity"];
[theAnimation2 setValue:@"animation2" forKey:@"id"];   
theAnimation2.delegate = self;
Check which one was called in delegate method:

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    if([[anim valueForKey:@"id"] isEqual:@"animation1"]) {
        NSLog(@"animation1");
    }
    if([[anim valueForKey:@"id"] isEqual:@"animation2"]) {
        NSLog(@"animation2");
    }
}

CAAnimation animationDidStop example.
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag {
//NSLog(@"First Animation stopped");

if (anim ==[topHalfCharLayerFront animationForKey:@"topCharAnim"]) {
    NSLog(@"Top Animation is: %@", anim);
    topHalfCharLayerFront.hidden = YES;
    [bottomHalfCharLayerFront addAnimation:[self bottomCharFlap:bottomHalfCharLayerFront] forKey:@"bottomCharAnim"];
    bottomHalfCharLayerFront.hidden = NO;
}

else if ((anim ==[bottomHalfCharLayerFront animationForKey:@"bottomCharAnim"])) {

    NSLog(@"Bottom Animation is: %@", anim);

}

End of CAAnimation animationDidStop example article.