UIKit Dynamics - Attachment Behaviour Tutorial in iOS8 with Swift

The UIAttachmentBehavior class can be used to create a connection between two items or between an item and a anchor point. In this tutorial a view is attached to an anchor point, this anchor point can be moved by using a tap gesture, This tutorial is built in iOS 8.1 with Xcode 6.1

Open Xcode and create a new Single View Application. For product name, use IOS8SwiftAttachBehaviourTutorial 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 View from the Object Library to the main View. Change the background color to black in the Attribute Inspector. Go to the size inspector and fill in the following values.

Add another View and change the background color to blue. Also go to the size inspector and fill in the following values.

he small, black view will be the anchor where the blue view will be attached to. Next, add a Tap Gesture Recognizer to the main View. The Storyboard will look like this. 

elect the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the small,black View to the ViewController class and create the following Outlet.

trl and drag from the blue View to the ViewController class and create the following Outlet.

Ctrl and drag from the Tap Gesture Recognizer and create the following Action

o to the ViewController.swift file and create the following properties.

var anchorPoint: CGPoint!
var attachment: UIAttachmentBehavior!
var animator: UIDynamicAnimator!
var gravity: UIGravityBehavior!

hange the viewDidLoad method to

override func viewDidLoad() {
    // 1
    anchorPoint = smallView.center
    // 2
    attachment = UIAttachmentBehavior(item: blueView, attachedToAnchor: anchorPoint)
    attachment.length = 100
    attachment.frequency = 10
    attachment.damping = 5
    // 3
    animator = UIDynamicAnimator(referenceView: view)
    // 4
    gravity = UIGravityBehavior(items: [blueView])
  1. The anchorPoint is set to the center of the small Vie
  2. he blueView is attached to the anchor point and the length,frequency and damping properties are set
  3. The attachment behaviour is added to the dynamic animator
  4. The gravity behaviour is also added to the dynamic animator

Next, implement the  handleTap method

@IBAction func handleTap(sender: UITapGestureRecognizer) {
    attachment.anchorPoint = sender.locationInView(view)
    smallView.center = sender.locationInView(view)

he anchorPoint and the center location of the smallView are updated to the location of the tap. Build and Run the project, Tap in the main view to update the anchor point.

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