Add Snap Behaviour Tutorial in iOS8 with Swift

As part of UIKit Dynamics you can add Snap Behavior to a view, which allows it  to be “snapped” to a specific location. The view will move to its new position as if it is pulled by a spring. In this tutorial we will let the user click on the screen to "snap" an image into place. This tutorial is built for iOS 8.1 and Xcode 6.1.

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

Go the Storyboard and drag a Image View to the main view, Go to the Size Inspector and set the size to 100 by 100 points. We need a image to insert in our Image View. Download this image, unpack it and add it to the project.

Select the Image View, go to the Attributes Inspector and add the apple.jpg file to Image field.

The Storyboard should now look like this.

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

Go to the ViewController.swift file and add the following properties

var animator:UIDynamicAnimator!
var snapBehaviour:UISnapBehavior!

The animator property provides physics-related capabilities for its item and the snapBehaviour property will be applied to the Image View later on. Next, change the viewDidLoad method to

override func viewDidLoad() {
    // Create the Tap Gesture Recognizer
    var tapGesture = UITapGestureRecognizer(target: self, action: Selector("userHasTapped:"))
    // Create the Dynamic Animator
    animator = UIDynamicAnimator(referenceView: self.view)

We have created a Tap Gesture Recognizer, which will call the useHasTapped method when the user taps on the screen. The Dynamic Animator is created with the main view as its reference view. Next, implement the userHasTapped method

func userHasTapped(tap:UITapGestureRecognizer) {
    var touchPoint = tap.locationInView(self.view)
    if snapBehaviour != nil {
    snapBehaviour = UISnapBehavior(item: imageView, snapToPoint: touchPoint)
    snapBehaviour.damping = 0.3

First we capture the point where the user has touched the screen. There can be only one Snap Behaviour instance active so we check if there is already a behaviour active. If so, we will remove this behaviour. Next we initialize our Snap Behaviour with the item:snapToPoint initializer. The item is our Image View and the point to snap to is the user's touch input. The damping property is the amount of oscillation the item has of the end of the snap animation. Finally, the Snap Behaviour is added to the Dynamic Animator. Build and Run the project, click anywhere on the screen to "snap" the image to its new location.

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