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
Here's a solution in Swift:
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 atbeginTime
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 fromCACurrentMediaTime()
, e.g.:Use KVC. setValue for Key for every animation. After that in animationDidStop you can define what animation has been stopped and run next in chain.
tl;dr: You need to manually add each animation after the previous finishes.
There is no built in way to add sequential animations. You could set the delay of each animation to be the sum of all previous animations but I wouldn't recommend it.
Instead I would create all the animations and add them to a mutable array (using the array as a queue) in the order they are supposed to run. Then by setting yourself as the animations delegate to all the animations you can get the
animationDidStop:finished:
callback whenever an animation finishes.In that method you will remove the first animation (meaning the next animation) from the array and add it to the layer. Since you are the delegate you will get a second animation when that one finishes in which case the
animationDidStop:finished:
callback will run again and the next animation is removed from the mutable array and added to the layer.Once the array of animations is empty, all animations will have run.
Some sample code to get you started. First you set up all your animations:
Then in the delegate callback you simply apply the next animation again
I'm using a custom key
layerToApplyAnimationTo
so that each animation knows its layer (it works just bysetValue:forKey:
andvalueForKey:
).Either David's approach or the beginTime property are ok for chaining animations. See http://wangling.me/2011/06/time-warp-in-animation.html - it clarifies the use of beginTime and other CAMediaTiming protocol properties.