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 10 and built for iOS 12.Open Xcode and create a new Single View App.

For product name, use IOSSpringAnimationTutorial 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 Resolve Auto Layout Issues button and select Reset to Suggested Constraints.

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 IOSSpringAnimationTutorial at the ioscreator repository on Github.