iOS UIView chained animations

Animations make everything look better, and lucky for us there is a UIView animation framework available inside UIKit:

Provide the total duration, then the animations you want and finally do something when the animation is completed.

The tricky part is chaining animations, using the completions to start the next animation:

We can do better and increase the readability of our animations. The end result will look something like this:

  1. The duration per step is specified in the constructor of the AnimationSequence and will be used for each step.
  2. Add all the steps you need for your animation. The order the steps are executed is the order in which you type them!
  3. Optionally, specify something to do when all your animations complete.

First we need a class to describe what an animation step looks like, the ViewAnimationStep:

It wraps the UIView animation by taking in a TimeInterval and the animations you want.

The next step is a way to represent the animation sequence:

The main parts are:

  1. The Array of ViewAnimationStep storing our steps.
  2. The TimeInterval that will be used for each step. Note that each step will take the same time. Different duration for each step is out of the scope of this post, but can definitely be done.
  3. doStep creates a new ViewAnimationStep and adds it to our Array.
  4. Finally, the execute(). It will pull each step from the array one by one and execute it. Once it runs out of steps it will call the completion to let you know there are no more steps.

There is a huge list of properties that can be animated, check for more information.

Animate all the things!