This post is for LearnSwiftLA members as a reference to my talk. Slides can be found here.

iOS Animation Basics

Birth of a UIViewController

  1. viewDidLoad
  2. viewWillAppear
  3. viewDidAppear

Lets start

We’ll start off with something simple, animating a UILabel. We’ll place it in the middle of our View Controller, and in code after we set the IBOutlet we’ll set up viewWillAppear so our UILabel is off screen while the view is appearing.

  override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)

heading.center.x -= view.bounds.width
username.center.x -= view.bounds.width
password.center.x -= view.bounds.width
}

center is the center point of the frame and x is the x-coordinate. So when we subtract center.x by view.bounds.width we’re basically telling our UILabel to move completely off screen.

iPhone Diagram

If we run our app now, we’ll see our UILabel is nowhere to be seen.

Disappearing Label

Now we’ll set up our first animation! We need our UILabel to show up where we set it up in our storyboard. To do this we’ll use viewDidAppear.

  override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

UIView.animate(withDuration: 0.5) {
self.heading.center.x += self.view.bounds.width
}
}

We’re undoing the changes in viewWillAppear but we’re animating the change inside viewDidAppear

If we added another label below and wanted to animate it, we could also give it a delay

UIView.animate(withDuration: 0.5, delay: 0.3, options: [], animations: {
self.username.center.x += self.view.bounds.width
}, completion: nil)