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 made with Xcode 8.3.3 and built for iOS 10.3.
Open Xcode and create a new Single View Application.
For product name, useIOS10SnapBehaviourTutorialand 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 theStoryboardand drag an 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. Downloadthisimage, 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 theViewController.swiftfile and add the following properties
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 theviewDidLoadmethod to
A Tap Gesture Recognizer is created, which will call the userHasTapped method when the user taps on the screen. The Dynamic Animator is created with the main view as its reference view. Next, implement theuserHasTappedmethod
First the point is captured 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 the Snap Behaviour is initialized with theitem:snapToPointinitializer. 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 Runthe project, click anywhere on the screen to “snap” the image to its new location.
You can download the source code of theIOS10SnapBehaviourTutorialat the ioscreator repository onGithub