How to chain different CAAnimation in an iOS application

torhector2 picture torhector2 · Jul 31, 2012 · Viewed 15.9k times · Source

I need to chain animations, CABasicAnimation or CAAnimationGroup but I don't know how to do it, the only that I do is that all the animation execute at the same time for the same layer.

How could I do it?

For example, a layer with its contents set to a car image:

1st: move X points to right

2nd: Rotate 90ª to left

3rd: Move X point

4th: Scale the layer

All this animations must be executed in a secuencial way, but I can't do it :S

BTW: I am not english, sorry if I made some mistakes in my grammar :D

Answer

Duncan C picture Duncan C · Jul 31, 2012

What david suggests works fine, but I would recommend a different way.

If all your animations are to the same layer, you can create an animation group, and make each animation have a different beginTime, where the first animation starts at beginTime 0, and each new animation starts after the total duration of the animations before.

If your animations are on different layers, though, you can't use animation groups (all the animations in an animation group must act on the same layer.) In that case, you need to submit separate animations, each of which has a beginTime that is offset from CACurrentMediaTime(), e.g.:

CGFloat totalDuration = 0;
CABasicAnimation *animationOne = [CABasicAnimation animationWithKeyPath: @"alpha"];
animationOne.beginTime = CACurrentMediaTime(); //Start instantly.
animationOne.duration = animationOneDuration;
...
//add animation to layer

totalDuration += animationOneDuration;

CABasicAnimation *animationTwo = [CABasicAnimation animationWithKeyPath: @"position"];
animationTwo.beginTime = CACurrentMediaTime() + totalDuration; //Start after animation one.
animationTwo.duration = animationTwoDuration;
...
//add animation to layer

totalDuration += animationTwoDuration;


CABasicAnimation *animationThree = [CABasicAnimation animationWithKeyPath: @"position"];
animationThree.beginTime = CACurrentMediaTime() + totalDuration; //Start after animation three.
animationThree.duration = animationThreeDuration;
...
//add animation to layer

totalDuration += animationThreeDuration;