Spring Animation Tutorial in iOS8 with Swift

Spring animations simulates "springy" motion. The animated object will move to a new locatiion and the jiggles before setting into place. In this tutorial we bounce a label sideways. This tutorial is built for iOS8.1 and Xcode6.1

Open Xcode and create a new Single View Application. For product name, use IOS8SwiftSpringAnimationTutorial 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 and drag a Label from the Object Library to the View Controller. Change the background color of the main view to light-gray and the background color of the label to yellow. Next, drag a button to the main view and change the title of the label to "Animate now". Select both the button and the label and select the "Resolve Auto Layout Issues" button at the bottom-right(3rd button) and select Add Missing 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 so we know which side the label is.

var labelPositionisLeft = true

Next, implement the animateLabel method.

UIView.animateWithDuration(0.5, delay: 0.5, usingSpringWithDamping: 0.5, initialSpringVelocity: 0, options: nil, animations: {
    if self.labelPositionisLeft {
      self.label.center.x = self.view.bounds.width - 100
    else {
      self.label.center.x = 100
    }, completion: nil)
    labelPositionisLeft = !labelPositionisLeft

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

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