Note from Ray: This is an abbreviated chapter from iOS Animations by Tutorials released as part of the Spring Swift Fling to give you a sneak peek of what’s inside the book. We hope you enjoy! :]
Animation is a critical part of your iOS user interfaces. Animation draws the user’s attention toward things that change, and adds a ton of fun and polish to your apps UI.
Even more importantly, in an era of “flat design”, animation is one of the key ways to make your app stand apart from others.
In this tutorial, you’ll learn how to use UIView animation to do the following:
- Set the stage for a cool animation.
- Create move and fade animations.
- Adjust the animation easing.
- Reverse and repeat animations.
There’s a fair bit of material to get through, but I promise it will be a lot of fun. Are you up for the challenge?
All right – time to get animating!
Getting Started
Start by downloading the starter project for this tutorial, which represents the login screen for a fictional airline – “Bahama Air”.
Build and run your project in Xcode and you’ll see the following:
The app doesn’t do much right now – it just shows a login form with a title, two text fields, and a big friendly button at the bottom.
There’s also a nice background picture and four clouds. The clouds are already connected to outlet variables in the code.
Open ViewController.swift and have a look inside. At the top of the file you’ll see all the connected outlets and class variables. Further down, there’s a bit of code in viewDidLoad()
, which initializes some of the UI. The project is ready for you to jump in and shake things up a bit!
Enough with the introductions – you’re undoubtedly ready to try out some code!
Your First Animation
Your first task is to animate the form elements onto the screen when the user opens the application. Since the form is now visible when the app starts, you’ll have to move it off of the screen just before your view controller makes an appearance.
Add the following code to viewWillAppear()
:
heading.center.x -= view.bounds.width username.center.x -= view.bounds.width password.center.x -= view.bounds.width |
This moves each of the form elements outside the visible bounds of the screen, like so:
Since the code above executes before the view controller appears, it will look like those text fields were never there in the first place.
Build and run your project to make sure your fields truly appear off-screen just as you had planned:
Perfect – now you can animate those form elements back to their original locations via a delightful animation.
Add the following code to the end of viewDidAppear()
:
UIView.animateWithDuration(0.5, animations: { self.heading.center.x += self.view.bounds.width }) |
To animate the title in you call the UIView
class method animateWithDuration(_:animations:)
. The animation starts immediately and animates over half a second; you set the duration via the first method parameter in the code.
It’s as easy as that; all the changes you make to the view in the animations closure will be animated by UIKit.
Build and run your project; you should see the title slide neatly into place like so:
That sets the stage for you to animate in the rest of the form elements.
Since animateWithDuration(_:animations:)
is a class method, you aren’t limited to animate just one specific view; in fact you can animate as many views as you want in your animations closure.
Add the following line to the animations
closure:
self.username.center.x += self.view.bounds.width |
Build and run your project again; watch as the username field slides into place:
Delayed Animations
Seeing both views animate together is quite cool, but you probably noticed that animating the two views over the same distance and with the same duration looks a bit stiff. Only kill-bots move with such absolute synchronization! :]
Wouldn’t it be cool if each of the elements moved independently of the others, possibly with a little bit of delay in between the animations?
First remove the commented out line of code below that animates username
:
UIView.animateWithDuration(0.5, animations: { self.heading.center.x += self.view.bounds.width // self.username.center.x += self.view.bounds.width }) |
Then add the following code to the bottom of viewDidAppear()
:
UIView.animateWithDuration(0.5, delay: 0.3, options: nil, animations: { self.username.center.x += self.view.bounds.width }, completion: nil) |
The class method you use this time looks familiar, but it has a few more parameters to let you customize your animation:
duration
: The duration of the animation.delay
: The amount of seconds UIKit will wait before it starts the animation.options
: A bitmask value that allows you to customize a number of aspects about your animation. You’ll learn more about this parameter later on, but for now you can pass nil to mean “no options.”animations
: The closure expression to provide your animations.completion
: A code closure to execute when the animation completes; this parameter often comes in handy when you want to perform some final cleanup tasks or chain animations one after the other.
In the code you added above you set delay
to 0.3
to make the animation start just a hair later than the title animation.
Build and run your project; how does the combined animation look now?
Ahh – that looks much better. Now all you need to do is animate in the password
field.
Add the following code to the bottom of viewDidAppear()
:
UIView.animateWithDuration(0.5, delay: 0.4, options: nil, animations: { self.password.center.x += self.view.bounds.width }, completion: nil) |
Here you’ve mostly mimicked the animation of the username
field, just with a slightly longer delay.
Build and run your project again to see the complete animation sequence:
That’s all you need to do to animate views across the screen with a UIKit animation!
That’s just the start of it – you’ll be learning a few more awesome animation techniques in the remainder of this tutorial!
Animatable Properties
Now that you’ve seen how easy animations can be, you’re probably keen to learn how else you can animate your views.
This section will give you an overview of the animatable properties of a UIView
, and then guide you through exploring these animations in your project.
Not all view properties can be animated, but all view animations, from the simplest to the most complex, can be built by animating the subset of properties on a view that do lend themselves to animation, as outlined in the section below.
Position and Size
You can animate a view’s position and frame in order to make it grow, shrink, or move around as you did in the previous section. Here are the properties you can use to modify a view’s position and size:
bounds
: Animate this property to reposition the view’s content within the view’s frame.frame
: Animate this property to move and/or scale the view.center
: Animate this property when you want to move the view to a new location on screen.
Don’t forget that Swift lets you adjust single members of structures as well. This means you can move a view vertically by changing center.y or you can shrink a view by decreasing frame.size.width
.
Appearance
You can change the appearance of the view’s content by either tinting its background or making the view fully or semi-transparent.
backgroundColor
: Change this property of a view to have UIKit gradually change the tint of the background color over time.alpha
: Change this property to create fade-in and fade-out effects.
Transformation
Transforms modify views in much the same way as above, since you can also adjust size and position.
transform
: Modify this property within an animation block to animate the rotation, scale, and/or position of a view.
These are affine transformations under the hood, which are much more powerful and allow you to describe the scale factor or rotation angle rather than needing to provide a specific bounds or center point.
These look like pretty basic building blocks, but you’ll be surprised at the complex animation effects you’re about to encounter!
Animation Options
Looking back to your animation code, you were always passing in nil to the options
parameter.
options
lets you customize how UIKit creates your animation. You’ve only adjusted the duration
and delay
of your animations, but you can have a lot more control over your animation parameters than just that.
There’s a list of options declared in the UIViewAnimationOptions
enumeration that you can combine in different ways for use in your animations.
Repeating
You’ll first take a look at the following two animation options:
.Repeat
: Enable this option to makes your animation loop forever..Autoreverse
: Enable this option only in conjunction with.Repeat
; this option repeatedly plays your animation in forward then in reverse.
Modify the code that animates the password field viewDidAppear()
to use the .Repeat
option as follows:
UIView.animateWithDuration(0.5, delay: 0.4, options: .Repeat, animations: { self.password.center.x += self.view.bounds.width }, completion: nil) |
Build and run your project to see the effect of your change:
The form title and username field fly in and settle down in the center of the screen, but the password field keeps animating forever from its position offscreen.
Modify the same code you changed above to use both .Repeat
and .Autoreverse
in the options parameter as follows:
UIView.animateWithDuration(0.5, delay: 0.4, options: .Repeat | .Autoreverse, animations: { self.password.center.x += self.view.bounds.width }, completion: nil) |
Build and run your project again; this time the password field just can’t make up its mind about staying on the screen!
Animation Easing
In real life things don’t just suddenly start or stop moving. Physical objects like cars or trains slowly accelerate until they reach their target speed, and unless they hit a brick wall, they gradually slow down until they come to a complete stop at their final destination.
The image below illustrates this concept in detail:
To make your animations look more realistic, you can apply the same effect of building momentum at the beginning and slowing down before the end, known in general terms as ease-in and ease-out.
You can choose from four different easing options:
.Linear
: This option applies no acceleration or deceleration to the animation..CurveEaseIn
: This option applies acceleration to the start of your animation..CurveEaseOut
: This option applies deceleration to the end of your animation..CurveEaseInOut
: This option applies acceleration to the start of your animation and applies deceleration to the end of your animation.
To better understand how these options add visual impact to your animation, you’ll try a few of the options in your project.
Modify the animation code for your password field once again with a new option as follows:
UIView.animateWithDuration(0.5, delay: 0.4, options: .Repeat | .Autoreverse | .CurveEaseOut, animations: { self.password.center.x += self.view.bounds.width }, completion: nil) |
Build and run your project; notice how smoothly the field decelerates until it reaches its rightmost position, before returning to the left side of the screen:
This looks much more natural since that’s how you expect things to move in the real world.
Now try the opposite: ease-in the animation when the field is still outside of the screen by modifying the same code as above to change the .CurveEaseOut
option to .CurveEaseIn
as follows:
UIView.animateWithDuration(0.5, delay: 0.4, options: .Repeat | .Autoreverse | .CurveEaseIn, animations: { self.password.center.x += self.view.bounds.width }, completion: nil) |
Build and run your project; observe how the field jumps back from its rightmost with robotic vigor. This looks unnatural and isn’t as visually pleasing as the previous animation.
You’ve seen how the various animation options affect your project and how to make movements look smooth and natural.
Now that you have some experience with animation curves, change the options on the piece of code you’ve been playing with back to nil:
UIView.animateWithDuration(0.5, delay: 0.4, options: nil, animations: { self.password.center.x += self.view.bounds.width }, completion: nil) |
And that’s it – you now understand how to use UIView animation API – so go forth and add some cool animations in your apps!
Where To Go From Here?
Now that you know how basic animations work, you’re ready to tackle some more dazzling animation techniques.
Animating views from point A to point B? Pshaw – that’s so easy! :]
If you want to learn more, check out our book iOS Animations by Tutorials. In the book, you’ll learn how to animate with springs, transitions, keyframe animations, CALayer animations, Auto Layout constraint animations, view controller transition animations, and more.
We hope you enjoyed this tutorial, and if you have any questions or comments, please join the forum discussion below!
UIView Animation with Swift Tutorial is a post from: Ray Wenderlich
The post UIView Animation with Swift Tutorial appeared first on Ray Wenderlich.