Chain Animations in Swift

One animation after another

Photo by JJ Ying on Unsplash

Prerequisites:

Terminology

UIView: An object that manages the content for a rectangular area on the screen

The challenge

You might well have dabbled with animations in Swift. Good for you! They are fun, and we can see a problem developing if we start to chain animations using animateWithDuration:animations:completion:

Click for Gist

The example

Let’s see an animation of a rectangle coming onto the screen, rotating and zooming and then then making a swift exit off the side of the screen. Something a little like the following:

Click for Gist
  • is difficult to maintain
  • that I’m not really sure what is going to happen when reading the code

Step in the animateKeyframes

The method creates an animation block to be used in keyframe animations. The class signature is slightly intimidating, an man there are a large number of UIView.KeyframeAnimationOptions within that.

animateKeyframes(withDuration:delay:options:animations:completion:)
Click for Gist
addKeyframe(withRelativeStartTime:relativeDuration:animations:)

Did you know

You can overlap the keyframes! There’s nothing wrong with that, and you can certainly make a number of fun effects doing so! Awesome!

Conclusion:

We’ve all used completion handlers to manage the flow of data within our App. This is usually a great solution, and certainly won’t cause you irretrievable issues in your App. However, the programmers pyramid of doom makes code difficult to maintain and add features to in the future?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store