UIView Animations Tutorial: Practical Recipes

In this UIView animations tutorial, you’ll learn to build practical recipes for your iOS apps using the UIKit framework. By Nick Bonatsakis.

Leave a rating/review
Download materials
Save for later
Share
You are currently viewing page 3 of 3 of this article. Click here to view the first page.

Adding Color Change Animations

Your animation recipes app is now pretty functional, but the interface still looks a bit dry. For your final trick, you'll wire up the Change Color button to a method that animates the background color of the main interface view to a random color.

Start by opening UIView+Animations.swift one last time, and add the following method:

func changeColor(to color: UIColor, duration: TimeInterval, 
                 options: UIView.AnimationOptions) {
  UIView.animate(withDuration: duration, delay: 0, options: options, animations: {
    self.backgroundColor = color
  }, completion: nil)
}

Through the magic of Core Animation, animating from one color to another is very easy, since the framework does all the heavy lifting of interpolating from the existing color to the new color. Because backgroundColor is an animatable property of UIView, this method simply wraps the setting of its value in an animation block and Core Animation does the rest.

Next, open ViewController.swift and add the following property at the top of the class:

let colors: [UIColor] = [.white, .red, .green, .orange, .yellow, .lightGray, .darkGray]

Now, add the following code to changeBackgroundColor():

view.changeColor(to: colors.randomElement()!, duration: 1.0, 
                 options: selectedCurve.animationOption)

Here, you simply invoke changeColor(to:duration:options:) on the root view to animate to a new, randomly selected color.

Build and run one last time, then tap Change Color a few times to see the view animate through various background colors.

Where to Go From Here?

You can download a completed version of the sample project using the Download Materials button at the top or bottom of the tutorial.

UIKit provides quite a powerful way to animate views and playing with the properties can give you some really cool effects with only a few lines of code. These effects are perfect for tool and utility-type apps and adding them as extensions of UIView makes your code more readable and lets you focus on your app logic.

I hope you enjoy your experimentations with UIView animations and look forward to seeing you use them in your apps!

If you have any questions or comments about UIView animation, please join the forum discussion below!