Animate View Auto Layout iOS Tutorial

With the introduction of the Adaptive Layout 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 the Auto Layout constraints will be updated to enable the view movement. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOS12AnimateViewsTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

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.

Select the red View and select the Auto Layout Add New Constraints button. Pin the Button to the top and and left. Select the width and height constraints. Select “Add 4 constraints.

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.

Select the Assistant Editor and make sure the ViewController.swift 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: Any) {
    // 1
    let newConstraint = NSLayoutConstraint(item: redView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1.0, constant: self.view.frame.width/2)
            
    // 2
    UIView.animate(withDuration: 2.0, delay: 0.0, options: .curveEaseOut , animations: {
            self.view.removeConstraint(self.leadingConstraint)
            self.view.addConstraint(newConstraint)
            self.view.layoutIfNeeded()
    }, 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 the 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 IOS12AnimateViewsTutorial at the ioscreator repository on Github.