Wednesday, June 12, 2013

CAAnimation animationDidStart example in Objective C (iOS).

CAAnimation animationDidStart

Called when the animation begins its active duration.

- (void)animationDidStart:(CAAnimation *)theAnimation

Parameters of [CAAnimation animationDidStart]
theAnimation
The CAAnimation instance that started animating.

CAAnimation animationDidStart example.
//--------------------------------------------------------------------------------------------------

#pragma mark - CAAnimation Delegate Methods

//--------------------------------------------------------------------------------------------------

- (void)animationDidStart:(CAAnimation *)theAnimation
{
    [CATransaction begin];
    [CATransaction setValue:(id)kCFBooleanTrue
                     forKey:kCATransactionDisableActions];

    // Set the layer's target position here.       

    [CATransaction commit];
}

Example of [CAAnimation animationDidStart].
What's happening is that you're seeing the animation in the presentation layer. However, that doesn't update the actual position of your layer. So, once the animation finishes, you see the layer as it was because it hasn't changed.

It's really worth reading the "Core Animation Rendering Architecture". Otherwise this can be very confusing.

To fix it, set a delegate to your CABasicAnimation as follows:

[animation setDelegate:self];

Then, create a method to set your target properties that you want when the animation completes. Now, here's the confusing part. You should do this on animationDidStart not animationDidStop. Otherwise, the presentation layer animation will finish, and you'll get a flicker as you see the calayer in the original position then it jumps - without animation - to the target position. Try it with animationDidStop and you'll see what I mean.

I hope that's not too confusing!

- (void)animationDidStart:(CAAnimation *)theAnimation
{
    [calayer setWhateverPropertiesExpected];
}

End of CAAnimation animationDidStart example article.