How to Get Started With iOS Animation (Part 1)

How to animate view components

Quang NGO
Better Programming

--

Photo by Cosmic Timetraveler on Unsplash

Animation is essential to make our apps enjoyable and professional. Users tend to trust and engage more with your app if they feel that the developer has invested effort and been meticulous in making the app more user friendly.

In this three-part series, we will see a complete stack of animations we can do in iOS:

  • View animation. In this first article, we’ll create a view and make the view’s component move in and around.
  • Movie-like animation. In this article, we will learn how to implement the Lottie framework and image sequence. At the end, we will compare video, GIF, image sequence, coding animation, and the Lottie framework.
  • Transition animation. In this article, we will touch the final and the most complicated part of iOS animation: view controller transition animation.

Prerequisite: The reader should know how to create view components like UIView, UIButton, and UIImageView.

During this first part, we will see how to implement all recommended ways of making a view component animated. Furthermore, we analyze the limit and use cases of each method.

Since one animated image is worth a thousand words, here’s the final result (actually we will add some more user’s interactive animation as a bonus):

Setup for This Tutorial

Before diving into the animations, we must initialize some view components and add them to the main view. This is the beginning point of all our animations. Please add this code in your initial view controller:

Basically, what we are doing here is inserting the app logo image and open button (hidden) in the centre of the view. We also added a car ImageView at the footer of our screen. Here’s what’s we have now:

Before diving into the animation code, it’s worth mentioning that creating an animation needs a lot of trial and error. We need to test many times to find out the perfect duration, frame timing, position, and other parameter values. To facilitate the test, we should use the slow-motion tool of the simulator (Simulator -> Debug -> Slow Animations) to monitor the animation.

Simplest Form of View Animation: UIView.animated function

The easiest way to animate a view is by using UIView.animated function. Here we want to do two things: move the app logo “Animation” to the top and fade in the Open button.

Add this function to your current code:

As you may see, this function is quite simple. It contains three inputs:

  • withDuration: Specifies the duration of the animation. Here we want to move the logo in one second.
  • animations: Describes the final state of this animation. Here we specify the final position (frame) of our logo image view. The function itself will interpolate the origin frame value and destination frame value to animate the action.
  • completion (optional): This is a completion handler that informs us of whether the animation sequence was finished or not. Here we make it our own completion.

Now we execute this function in viewDidAppear. Plus, when the animated logo finishes, we also use the UIView.animate function to fade in the Open button:

Now run our app. We should see this:

This function is able to work with frame, bound, centre, transform, alpha, and background colour of a view.

UIView’s animation function has some variants that allow specifying more animation properties, like damping, animation options (easy in, easy out, etc.), delay, and so on. We recommend you read Apple’s documentation to learn more details.

Animating Layer Property: CABasicAnimation

CABasicAnimation is an object that provides basic, single-keyframe animation capabilities for a layer property. You create an instance of CABasicAnimation using the inherited init(keyPath:) method, specifying the key path of the property to be animated in the render. Like the UIView.animated function, by specifying fromValue and toValue, Core Animation will interpolate the transition values and make the animation. You can consult the full list of key paths in the Core Animation Programming Guide, Appendix B and Appendix C.

We’ll use CABasicAnimation to animate drawing the line around the Open button. To do this, we use four steps:

  1. Create the Bezier path for that line.
  2. Inject that path into aCAShapeLayer.
  3. Create CABasicAnimation object by specifying our animation parameters.
  4. Execute this CABasicAnimation on our CAShapeLayer by using CATransaction.

Here’s the code:

The code looks intimidating, but actually most of it is for specifying our animation parameters like duration, start position, end position, timing easyInEasyOut, etc., and those values are found through trial and error.

We execute this function by replacing the completion of animateLogo with our function self.animateLoginButton(). We receive the result below (please ignore the car moving; we’ll do it later):

Based on what we just learned here, we can easily create a “shaking” animation based on a user’s touch. Basically, when the user touches the Animation logo, we want the logo to be shaken. As you may already have figured out, that animation will be a position type (go to left and to right), autoreverse, and loop about four or five times. The code should look like this:

To wire the tap event to this function, we can register a gesture recognizer to the logo image view in setupUI function:

logoImageView.isUserInteractionEnabled = true
logoImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(shakeLogo)))

Run the code, here’s the result when you tap on the logo image:

Animating With User’s Interaction

The most convenient way to interact with a view’s animation is to use UIViewPropertyAnimator. From Apple’s documentation:

“A UIViewPropertyAnimator object lets you animate changes to views and dynamically modify your animations before they finish. With a property animator, you can run your animations from start to finish normally or you can turn them into interactive animations and control the timing yourself. The animator operates on animatable properties of views, such as the frame, center, alpha, and transform properties, creating the needed animations from the blocks you provide.”

Actually, UIViewPropertyAnimator is relatively similar to the UIView.animated function. When we create this object, we must specify a block containing code that modifies the properties of one or multiple views, the timing curve, the duration, and a completion block to execute when animations finish.

We will apply this object to make the car’s animation. We would like to make it move to the right, then back to the left, infinitely. Plus, we need to catch the user’s tap gesture and then make the car move back. So basically we need three functions. One function runs when the user taps on the car, one makes the car run to the right, and a final one makes it move to the left:

Now we wire these functions to our view in viewDidAppear and add self.animateCarToRight(). In setupUI(), add the following:

carImageView.isUserInteractionEnabled = true
carImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(userTapOnCar)))

Run the app, and try tapping on the car to see it if it pulls back. Here’s the result:

Tapping on the car make it goes back

Where to Go From Here

You can download the code of this tutorial.

In this article, we learned how to animate a UIView using the UIView.animated function. We also saw how Core Animation can help us to draw layer animation using a Bezier path and CABasicAnimation. And finally, we figured out how to enable a user’s interaction with the animation.

We are now experts in animating the view’s components. In the next article, we aim to animate a sequence of images (movie-like animation), and in the final article, we’ll animate transitions between view controllers.

Here’s what we’ll have after the second part:

And in the final part, we animate the present transition and the dismiss transition. We also learn how to programmatically control the progress of this animation.

I hope you enjoyed this tutorial. See you again soon in the next part.

--

--

iOS Engineer. Passionate in improving mobile development environment. Sharing best practices and how to do better programming