Spring Animation iOS Tutorial

Spring animations simulates "springy" motion. The animated object will move to a new location and then jiggles before setting into place. In this tutorial a label will be bounced sideways.This tutorial is made with Xcode 9 and built for iOS 11.

Open Xcode and create a new Single View App.

For product name, use IOS11SpringAnimationTutorial 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 and drag a Label to the main view. Select the Label and select the Auto Layout pin button. Pin the Button to the top and left and click "Add 2 Constraints".

Drag a Button to the main view. Set the title of the button to Animate. Select the Button and select the Auto Layout align button. Select the "Horizontally in Container" checkbox and click "Add 1 Constraint".

Select the Button and select the Auto Layout pin button. Pin the Button to the top and and click "Add 1 Constraint".

The Storyboard should look like this.

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Label to the ViewController class and create the following Outlet

Ctrl and drag from the Button to the ViewController class and create the following Action

The label will bounce from left to right and back each time the button is pressed. Create a boolean property to indicate which is the current side of the label

var labelPositionisLeft = true

Implement the animateLabel method

@IBAction func startAnimation(_ sender: Any) {
    UIView.animate(withDuration: 0.5, delay: 0.5, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: .curveEaseInOut, animations: {
        if self.labelPositionIsLeft {
            self.label.center.x = self.view.bounds.width - 100
        }
        else {
            self.label.center.x = 100
        }
        self.labelPositionIsLeft = !(self.labelPositionIsLeft)
    }, completion: nil)
}

The damping ratio is a number between 0 and 1. The higher the number the "springier" the animation will be. The boolean is checked  at which side the label is and then the center is updated.

Build and Run the project, click the Animate button a few times and watch the label bounce to left and right.

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