Animations

In general, an animation by itself is simple to do - the challenge is mixing several of them into a bigger one.

Native UIKit methods

This snippet waits half a second and then moves objects across the screen through 1 second.

username.frame.origin.x = 300
    password.frame.origin.x = 300
    loginButton.alpha = 0
    UIView.animateWithDuration(1, delay: 0.5, options: .CurveEaseOut, animations: {
        username.frame.origin.x = 10
        password.frame.origin.x = 10
        loginButton.alpha = 1
    }, completion: {
        //Things to be done after the animation finishes, like doing another animation
    })

For your convenience, this assumes that we are not using AutoLayout, which is rarely the case. The actual code would be slightly different.

It results in something like this:

Available options:

Animatable properties of an object:

  • center

  • alpha

  • frame

  • bounds

  • transform

  • backgroundColor

  • contentStretch

The above looks more interesting than a static presentation, but the views getting animated at the same time, doesn’t create that great an effect. Let's animate them separatedly:

UIView.animateWithDuration(0.5, delay: 0.0, options: .CurveEaseOut, animations: {
        username.frame.origin.x = 10
    }, completion: nil)

    UIView.animateWithDuration(0.5, delay: 0.3, options: .CurveEaseOut, animations: {
        password.frame.origin.x = 10
    }, completion: nil)

    UIView.animateWithDuration(0.5, delay: 0.4, options: .CurveEaseOut, animations: {
        loginButton.alpha = 1
    }, completion: nil)

UIKit also has a method for spring animations:

UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.2, initialSpringVelocity: 10, options: nil, animations: {
        loginButton.bounds = CGRect(x: bounds.origin.x - 20, y: bounds.origin.y, width: bounds.size.width + 60, height: bounds.size.height)
    }, completion: nil)

We can do keyframe based animations like this:

UIView.animateKeyframesWithDuration(4, delay: 0, options: .CalculationModeCubic, animations: {
        UIView.addKeyframeWithRelativeStartTime(0.0, relativeDuration: 0.5) {
            //animation here
        }
        UIView.addKeyframeWithRelativeStartTime(0.5, relativeDuration: 0.5) {
            //here
        }
    }, completion: nil)

To do things like this:

Frameworks, and Uber

UIKit's methods are handy for simple things, but it can be overwhelming for complicated stuff. Luckily, there are several frameworks that wraps these methods, simplifying the process.

Uber's splash screen is just a clever use of 2D perspective and animations. You can read about it here: https://www.raywenderlich.com/133224/how-to-create-an-uber-splash-screen

Last updated