UIKit Dynamics Attachment Behaviour iOS Tutorial

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 made with Xcode 9 and built for iOS 11.

Open Xcode and create a new Single View App.

For product name, use IOS11AttachBehaviourTutorial 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 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.

The 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.

Select 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.

Ctrl 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

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

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

Change the viewDidLoad method to

override func viewDidLoad() {
    super.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)
    animator.addBehavior(attachment)
    
    // 4
    gravity = UIGravityBehavior(items: [blueView])
    animator.addBehavior(gravity)
  }
  1. The anchorPoint is set to the center of the small Vie
  2. The 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.location(in: view)
        smallView.center = sender.location(in: view)
    }

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