Swift Beginner's Guide to View Animations

Published Jan 13, 2016Last updated Feb 15, 2017
Swift Beginner's Guide to View Animations

Introduction

In this tutorial, you are going to learn how to use view animation and how to convert a simple view into an awesome view. How to make your app interesting, attractive, and fascinating.

We will cover some basic topics about animation and its properties, but I am sure after reading this tutorial you will have a good foundation in the bottomless sea of view animations

Topics you will learn in this tutorials

  • Setting your View for the awesome Animation
  • Animation Properties like:
    • CurveEaseInOut
    • CurveEaseIn
    • CurveEaseOut
    • CurveLinear
  • Animation Loops
  • Adjusting Animation
  • Spring Animation
  • ViewLifeCycle & many more...

Getting Started

First of all, download the Starter project.

Open up the starter project i.e "CoreAnimation_StarterProject". Build and run your project, and you will see a normal login page just like the image below

CoreAnimation_StarterProject

Now open up the open the StarterProject > MainStoryboard. You will see some ImageViews, Buttons and Labels placed up in a proper manner to make the view look and feel good.

The app does not do much, but here you will make the view more interesting. Open up the ViewController.swift file 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!

Add this function after ViewDidLoad()

override func viewWillAppear(animated: Bool)
{
   //Some Code here
}

This function will help you instantiate some code before the view will appear in the iDevice Screen, then add the following code inside the function viewWillAppear()

//Some Code here
loginLabel.center.y -= view.bounds.width
emailTextField.center.x -= view.bounds.width
passwordTextField.center.x += view.bounds.width

This will move each of the form elements outside the visible bounds of the screen, like so:
ViewAnimationStarterProject

Build and run your project to make sure your fields truly appear off-screen just as you planned:

Animation

Perfect! Now you can animate those form elements back to their original locations via a delightful animation.

To do so, add the function viewDidAppear()

override func viewDidAppear(animated: Bool)
{
   //Some Code here
}

This function will execute the code when the view is loaded from the nib file. Add the following code inside the function viewDidAppear()

UIView.animateWithDuration(2.0, animations: {
    self.loginLabel.center.y += self.view.bounds.width
})

What happens here is, you have animated the title as you have called the UIView class method animateWithDuration(_:animations:). The animation starts immediately and animates over two seconds; you set the duration via the first method parameter in the code.

It's really easy, as all the changes you make to the view in the animations closure will be animated by the UIKit.
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.

Ok, now you will set the stages to animate the rest of the elements, i.e. - email and password text field. Here, we will add some "Spring Velocity".

Open up ViewController.Swift, and take a look at the lines on viewDidAppear()

UIView.animateWithDuration(1.5, delay: 0.5, 
                           usingSpringWithDamping: 0.3, 
                           initialSpringVelocity: 0.5, 
                           options: [], animations: {
    self.emailTextField.center.x += self.view.bounds.width
    self.passwordTextField.center.x -= self.view.bounds.width
    }, completion: nil)

There are two key points in this piece of code.
First, you’ve animated two different properties at the same time! That was easier than you thought, right?

Secondly, you used a new animation method for the first time:
animateWithDuration(_:delay:usingSpringWithDamping:initialSpringVelocity:options:animations:completion:). Saying that method name too quickly just might injure your tongue! Ha, just kidding.

The above method looks much like the ones you used in the previous code for animating the Login label, but it has a couple of new parameters:

usingSpringWithDamping: This controls the amount of damping─or reduction─applied to the animation as it approaches its final state. This parameter accepts values between 0.0 and 1.0. Values closer to 0.0 create a bouncier animation, while values closer to 1.0 create a stiff-looking effect. You can think of this value as the stiffness of the spring.

initialSpringVelocity: This controls the initial velocity of the animation. A value of 1.0 sets the velocity of the animation to cover the total distance of the animation in the span of one second. Bigger and smaller values will cause the animation to have more or less velocity.

Build and run your project. It will look like this:

ViewAnimationProject

Great...

Now it's time to animate the Login button. Add the following code to viewWillAppear() to hide the button where the view appears

//This will make the view invisible when the view will appear
    loginButton.alpha = 0.0

Now in viewDidAppear () add these code

    UIView.animateWithDuration(1.0, delay: 2.0, 
                               options: [],
                               animations: {
        self.loginButton.alpha = 1.0
            }, completion: nil)

What you are doing is very simple. When the view appears, the
loginButton.alpha = 0.0 will execute, which will make the button invisible. To make the view visible again, set the alpha back to 1.0. Doing this will get you a simple fade-in, fade-out animation.

LoginButton

Run your code and enjoy your animation by altering the timings.

Till now you have learned the basics on how to animate elements. Let's go a step further and animate those clouds to complete the view.

First of all, set the clouds' alpha to 0.0 so that it will not appear when the view appears (just for a while to gain time to animate those beautiful clouds)

Add these lines in viewWillAppear()

cloud1.alpha = 0.0
cloud2.alpha = 0.0
cloud3.alpha = 0.0
cloud4.alpha = 0.0

and these in viewDidAppear() to get back those clouds back to your view with animation

UIView.animateWithDuration(0.5, delay: 0.6, options: [], animations: {
    self.cloud1.alpha = 1.0
    }, completion: nil)

UIView.animateWithDuration(0.5, delay: 0.8, options: [], animations: {
    self.cloud2.alpha = 1.0
    }, completion: nil)

UIView.animateWithDuration(0.5, delay: 1.0, options: [], animations: {
    self.cloud3.alpha = 1.0
    }, completion: nil)

UIView.animateWithDuration(0.5, delay: 1.2, options: [], animations: {
    self.cloud4.alpha = 1.0
    }, completion: nil)

Just like what you have done with login button. However, something is missing. Let's make the cloud move in a loop.

Add something like this additional function to your code─I will Explain it as we go.

func animateTheClouds(cloud : UIImageView) {
    let cloudMovingSpeed = 60.0/view.frame.size.width
    let duration = (view.frame.size.width - cloud.frame.origin.x) * cloudMovingSpeed
    UIView.animateWithDuration(NSTimeInterval(duration), delay: 0.0, options: .CurveLinear, animations: {
        cloud.frame.origin.x = self.view.frame.size.width
        }, completion: {_ in
            cloud.frame.origin.x = -cloud.frame.size.width
            self.animateTheClouds(cloud)
    })
}

This method has a similar implementation to the one that animates the clouds using UIKit. In fact, the first few lines of the above Code is used to set up the clouds' moving speed and duration.

In the second part of the above code, you just used speed and duration in animateWithDuration.

Finally, in your viewDidAppear(), call the function to animate those clouds by adding these lines just after the part where we've just added the fade-in animation

animateTheClouds(cloud1)
animateTheClouds(cloud2)
animateTheClouds(cloud3)
animateTheClouds(cloud4)

Add the above code after the line which shown below

.......
     UIView.animateWithDuration(0.5, delay: 1.2, options: [], animations: {
    self.cloud4.alpha = 1.0
    }, completion: nil)
//Add here

And you are done! Build and run your code─I hope you like the way things are animated!

enter image description here

Now you are ready to apply animations to UI Elements on your own, so take a shot at animating those beach birds like the view shown in the introduction.

Hope you enjoyed this tutorial, and stay tuned for more Swift animation tutorials!

Thank you.

Download the full project from here

Discover and read more posts from Abdul Karim
get started
Enjoy this post?

Leave a like and comment for Abdul

2
5
5Replies
superverse
10 months ago

Very helpFUl! thanks for sharing

Iavor Dekov
a year ago

Thank you for tutorial Abdul! I’m surprised with how simple it is to actually animate different UIViews. How do you animate the birds by the way?

Abhijeet
2 years ago

Good article Abdul…its easy to get and understood for new user in the IOS development at starting phase.

Show more replies

Get curated posts in your inbox

Read more posts to become a better developer