I’m sure most of you have already done some animations using UIView.animate. For those, who are new to it, the basic method is actually pretty straightforward:
The above method animates the view for 100 points to the right. The animation itself lasts 1 second.
Now, let’s say we want to change the color of the view, once that view arrives at its destination (stops animating):
We simply put another animation inside the completion of the first. Now, let’s say we want to add even more animations. After a while, our animation looks like this:
At this point you’re surely thinking, there must be a way to resolve this pyramid of doom. And there sure is.
Using the UIView’s animateKeyframes
In iOS 7 Apple introduced a new animation method named animateKeyframes, which creates an animation block object that can be used to set up keyframe-based animations.
The basic implementation requires the duration, initial delay and the animations itself:
Now, let’s add some animations. We do that using the addKeyframe method. It has three required parameters:
When should the animation start? Note that this value must be in the range from 0 to 1. This means, if we have a total duration for 5 seconds, and we want to start the animation after 2 seconds, we need to set the frameStartTime to 2/5.
How long the animation should last. Note that this value must be in the range from 0 to 1. If our animation should last 1 second, and the total animation duration is 5 seconds, we set this to 1/5.
A block that should contain the animations you want to perform.
Put it all together:
To construct our animation with keyFrames, we need to call the addKeyframe method inside the `animations` block of animateKeyframes. The result looks like this:
The animation options of the UIView.animateKeyframes are calculating the inter-frames between your animations. The main and most used ones are the following:
Simple linear calculation when interpolating between keyframe values.
Without interpolation – simply jumping to each new keyframe
Computing intermediate keyframe values using simple pacing algorithm. (Evenly paced animation)
Compute the intermediate keyframes using a default Catmull-Rom spline.
There’s a lot more to explore about animating with keyframes, for example overlapping keyframe animations and taking full advantage of the new animation options.