Basic UIView Animation Tutorial: Getting Started
Animations are everywhere in iOS. In this tutorial, you’ll learn to chain the basic UIView animations together to create incredibly satisfying effects! By Ehab Amer.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Basic UIView Animation Tutorial: Getting Started
25 mins
One of the coolest things about iOS apps is how animated they are. Views can nimbly fly across the screen, gracefully fade in and out, cleverly rotate around and rescale, and much, much more! UIView animation is everywhere in iOS, and it’s a big part of what makes iOS apps so much fun.
Thoughtfully chosen animations look great, and they can really bring your own iOS app to life. Better still, they’re also a great way to draw a user’s attention any time new or additional information becomes available in your app.
But maybe the best part about UIView animation is that it’s incredibly easy to implement. All it takes is a few lines of code, and you’re up and running!
In this tutorial, you’ll get a chance to go hands-on with UIView animation! You’ll create a simple app with a picnic theme: You’ll use animation to open the picnic basket, animate an interloping bug that’s snuck into the basket, then take decisive action, so your tasty picnic goodies stay bug-free!
As you’re doing this, you’ll learn to use the basic UIView animation APIs and to chain animations together for even more satisfying effects.
So grab your picnic basket; it’s time to get started!
What UIView Animation Does For You
To help you appreciate how nice and easy native UIView animation is, first review some of the steps you’d need to take if iOS didn’t provide built-in animation tools and you wanted to animate a view moving across the screen on your own:
- Schedule a method to be called in your app, once for every frame drawn.
- Determine the number of frames your animation should run based on its duration and then, for each frame:
- Calculate the new position of the view based on the view’s beginning and desired final destination, the time your animation will run, and how long it’s run so far.
- Update the view’s position, either by directly setting it or by updating the AutoLayout constraints that determine its position.
- When your animation has completed, or if it’s interrupted, clean up and make sure the final state of the view is correct.
- Calculate the new position of the view based on the view’s beginning and desired final destination, the time your animation will run, and how long it’s run so far.
- Update the view’s position, either by directly setting it or by updating the AutoLayout constraints that determine its position.
That’s all possible to do, but you’d likely think hard before implementing even a simple animation this way. And homegrown animations like this would get more complex as you added animations of different types, durations, and delays. Your code would become more complicated still as animations interacted. You’d end up micro-managing animation implementation details rather than working on meaningful code.
The great news is that UIView animations are extremely easy to use. Many view properties, such as a view’s frame (its size and position), its alpha (transparency), and its transform (scale, rotation, etc.), have built-in animation support. And best of all, instead of having to sweat all the frame-by-frame steps listed, using UIView animation, all you do is:
- Call one of the UIView animation methods and tell it how long your animation should run, along with some other simple parameters.
- Set up an animation block where you let UIKit know the final values of any properties you’d like to animate.
- There is no Step 3! :]
Once you’ve completed these 2 simple steps, UIView animation will manage all the fine details and complexities to deliver silky smooth animations on your behalf. Time to dive right in and see how to make this magic happen in code!
Getting Started
Use the Download Materials button at the top or bottom of this tutorial to download the starter project. Unzip the downloaded project, open the starter project, and take a look around: You’ll see that the starter project contains a view controller and a main storyboard pre-populated with the elements you’ll need. The outlets for each elements are already connected, so you can get right to work on the good stuff. You might also notice a sound file, which you’ll use for some extra fun at the end of this tutorial!
Open Main.storyboard, and check that the Document Outline is visible and expanded as shown below. If you don’t see this, either click the Show Document outline button, or choose Editor ▸ Show Document Outline to display it.
In the Document Outline, you’ll see the views you’ll be animating: The doors of your fancy picnic basket, a spiffy set of fabric napkins, a plate of tasty cheese, and a sneaky, picnic-crashing bug.
Build and run your app. After a moment, you’ll see the starter project showing your picnic basket with its lid closed:
Opening the Picnic Basket
You’re going to teach your picnic basket to open up in a nifty animated way. You’ll do this in two steps:
- Open up the picnic basket’s doors.
- Move aside the fabric napkins inside the picnic box. :]
Open ViewController.swift. After viewDidAppear(_:)
, add stubs for the methods you’ll use to perform these two steps:
func openBasket() {
}
func openNapkins() {
}
And then call both methods inside viewDidAppear(_:)
:
openBasket()
openNapkins()
Next, you’ll flesh out these methods, starting with the napkins. You’ll start here because it’s a bit simpler to animate views without constraints.
Open Main.storyboard and select the Basket Top and Basket Bottom views. Open the Attribute inspector and, in the Drawing section, tick the Hidden attribute checkbox. This will temporarily hide basket’s doors so they won’t block your view of the animating napkins.
Build and run your app once again. This time, you’ll see the fabric napkins inside the basket.
Now, open ViewController.swift again and add this code to openNapkins()
:
UIView.animate(withDuration: 1.0, delay: 1.2, options: .curveEaseOut, animations: {
var fabricTopFrame = self.fabricTop.frame
fabricTopFrame.origin.y -= fabricTopFrame.size.height
var fabricBottomFrame = self.fabricBottom.frame
fabricBottomFrame.origin.y += fabricBottomFrame.size.height
self.fabricTop.frame = fabricTopFrame
self.fabricBottom.frame = fabricBottomFrame
}, completion: { finished in
print("Napkins opened!")
})
Here’s what this does:
-
animate(withDuration:delay:options:animations:completion:)
defines an animation with a duration of 1 second, beginning after a delay of 1.2 seconds. You selected an “ease out” option, which produces an animation that progresses linearly through each frame until it approaches completion, at which point it slows down to give a more natural, less jarring effect. In other words, the napkins don’t “slam” open. - You use the
animation
block to specify which views and properties to animate. Notice that instead of having to deal with any details of how this animation will be rendered frame-by-frame, you simply declare the final value each animatable property will have when your animation is complete. Armed with these high-level instructions, UIView animation takes charge of all the low-level implementation details on your behalf: It handles all the frame-by-frame calculations, applies any easing, and even handles any interruptions that might occur. Hooray! - Finally, the
completion
block runs after the animation either completes naturally or is interrupted, giving you a chance to do any final clean up that might be needed. The completion block receives a boolean parameter, finished, that tells you whether the animation completed or not.
Before moving on, take a quick look at the different easing options UIView animation provides out of the box:
-
curveEaseInOut
: Property changes are slow at the beginning and at the end of the animation. -
curveEaseIn
: Property changes are slow at the beginning of the animation only. -
curveEaseOut
: Property changes are slow at the end of the animation only. -
curveLinear
: Property changes are equal during the whole animation.
Build and run again:
Sweet! Now when your app launches, the napkins animate to reveal the yummy picnic goodies in your basket (well, that plus an unwanted buggy… for now).