Animating Views with Auto Layout in iOS8 with Swift

With the introduction of the new Adaptive Layout in iOS 8, all views use Auto Layout by default. However, when animating views the constraints applied to a view prevents the ability to move this view using animation. In this tutorial we will update the Auto Layout constraints to enable the view movement. This tutorial is built for iOS 8 and Xcode 6.

Open Xcode and create a new Single View Application. For product name, use iOS8SwiftAnimatingViewTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

Go to the Storyboard. Drag a View from the Object Library to the main View and in the Attributes Inspector give it a red background color. Select the view and enter the following values in the Size Inspector.

Ctrl + Drag from the red View to the left and select "Leading Space to Container Margin". This will pin the red View to the left of the main view. Ctrl + drag from the red view to the top and select "Top Space to Top Layout Guide". This will pin the red view ti the top of the main view. Select the red View and drag it a few pixels inside the red view. Select the height and width options. This will keep the width and height of the red view equal. Finally, add a Button to the main View and place it below the red View somewhere in the centre. Give it a title of "Move". The storyboard should look like this.

Open the Assistant Editor and make sure the ViewController.swift file is visible. Ctrl + drag from the redView to the ViewController class and create the following outlet.

Ctrl + drag from the leading Constraint from the storyboard to the ViewController class and create the following Outlet.

Ctrl + drag from the Move Button from the Storyboard to the ViewController class and create the following Action.

Next, implement the moveButtonPressed Action method

@IBAction func moveButtonPressed(sender: UIButton) {
    // 1
    var newConstraint = NSLayoutConstraint(item: redView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1.0, constant: self.view.frame.width)
    // 2
    UIView.animateWithDuration(1.0, delay: 0.0, options: .CurveEaseOut , animations: {
      }, completion: nil)
    // 3
    leadingConstraint = newConstraint
  1. Using the NSLayoutConstraint initializer method, the leading constraint is set to the width of the main view, which puts the red image offscreen.
  2. The view is animated by removing teh  old and adding the new constraint. The layoutIfNeeded method is used to force the layout before drawing.
  3. The leading Contstraint is set to the new Constraint.

Build and Run the project, click the move button to move the red view offscreen.

You can download the source code of the iOS8SwiftAnimatingViewsTutorial at the ioscreator repository on Github