UIKit Dynamics and Swift Tutorial: Tossing Views

Bjørn Ruud
Learn how to toss your views with gestures and physics behaviors in this UIKit Dynamics tutorial!

Learn how to toss your views with gestures and physics behaviors in this UIKit Dynamics tutorial!

Update note: This tutorial was updated to Swift and iOS 8 by Bjørn Ruud. Original post by Tutorial Team member Tony Dahbura.

In this UIKit Dynamics tutorial, you’ll learn how to toss views off-screen with gestures in a natural feeling way.

You may have seen this technique popularized in the popular app Tweetbot.

This tutorial is a good fit for intermediate developers because it covers some neat effects, such as rotation and fly-away animations using the native UIKit framework.

But if you’re completely new to UIKit dynamics, don’t fear – this tutorial will guide you through step by step.

Without further ado, let’s get to tossing!

Note from Ray: Full credit for this technique goes to Orta Therox, the newest member of our new “Code Team” at raywenderlich.com. Orta created the original sample project that Tony polished and converted into this tutorial.

The Code Team is a group of expert-level coders that spend their waking hours coming up particularly cool demos to demonstrate advanced techniques. The Tutorial Team then converts the best demos into high quality tutorials. If you’re an expert-level iOS developer and joining the Code Team piques your interest, check out the details and get in touch!

Getting Started

Note: This section is optional for those who want to make the project from scratch. Experienced iOS developers might want to skip this section and proceed to the next section, “UIDynamicAnimator and UIAttachmentBehavior” where we have a starter project waiting for you.

Start up Xcode, select File\New\Project…, choose iOS\Application\Single View Application template, and click Next. Name the project DynamicToss, make sure the selected language is Swift, and set the device family to iPhone.

Now select the project name on the left and select the General at the top of the Xcode window. Under Deployment Info/Device Orientation uncheck the Landscape Left and Landscape Right checkboxes, because your app will only run in portrait mode.


Next, download an image that you’ll need for this project, courtesy of gameartguppy.com.


Unzip the file and add it to the Images asset catalog in your project.

Next, select Main.storyboard and go to the File Inspector in the utilities area on the right. To keep the scope of this tutorial small you will not use auto layout and size classes, so untick the Use Auto Layout checkbox. This will also disable size classes. In the dialog box that appears, choose to keep size class data for iPhone and select Disable Size Classes.

In the storyboard, add an image view to the default view controller and set the image to goldfish_feature. In the size inspector for the image view, set the following values: X=33, Y=137, Width=254, Height=172. Also, change the autoresizing mask to disable flexible height, width, right, and bottom margins. That means only the top and left margins stay “selected”.

Your screen should now look like this:


Next, drag two plain Views into your view controller that you will use to help track your gestures. Set them to the following settings:

  • View 1: (X=156, Y=219, Width=8, Height=8, Background=red)
  • View 2: (X=80, Y=420, Width=8, Height=8. Background=blue)

When done your view should look like this:


That covers the views you’ll need to set up in the storyboard. Next: on to some code!

Touch Handling

Open ViewController.swift and add the following properties to the class:

@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var redSquare: UIView!
@IBOutlet weak var blueSquare: UIView!

private var originalBounds = CGRect.zeroRect
private var originalCenter = CGPoint.zeroPoint

private var animator: UIDynamicAnimator!
private var attachmentBehavior: UIAttachmentBehavior!
private var pushBehavior: UIPushBehavior!
private var itemBehavior: UIDynamicItemBehavior!

You’ll connect the outlets in a moment. The other properties will control the image view’s movement and keep track of its state as the touch events go on.

Open Main.storyboard and right click (or control-click) on the View Controller. Drag from the circle to the right of the outlet named blueSquare onto the small blue square view and release the mouse. This links the property to the view object.

Do the same for the red square, and finally for the property named imageView, drag onto your jetpack-equipped goldfish. Your three view properties should now be linked, like this:


The red and blue squares will represent points that the UIKit dynamics physics engine uses to animate the image.

The blue square will simply represent where your touch began, i.e., where your finger first made contact with the screen. The red square will track your finger as it moves.

You’ll configure the dynamics so that when you move that point around, the image view physically animates to move in tandem.

There’s one final thing you need to do – set up a gesture recognizer for the view. Open ViewController.swift and add this new method to the file:

@IBAction func handleAttachmentGesture(sender: UIPanGestureRecognizer) {
  let location = sender.locationInView(self.view)
  let boxLocation = sender.locationInView(self.imageView)

  switch sender.state {
  case .Began:
    println("Your touch start position is \(location)")
    println("Start location in image is \(boxLocation)")

  case .Ended:
    println("Your touch end position is \(location)")
    println("End location in image is \(boxLocation)")


You’re going add a gesture recognizer to detect dragging, aka panning, and call this method when panning occurs. For now, this method simply displays the position of your finger in two coordinate systems (the view, and the image view).

To add the gesture recognizer, open Main.storyboard and drag a Pan Gesture Recognizer onto the View. Then control-drag from the Pan Gesture Recognizer up to your View Controller, and connect it to the handleAttachmentGesture: action.

Now build and run. Swipe or drag across the screen and you should see messages coming out on the debug window:

Your touch start position is (125.0,227.0)
Start location in image is (92.0,90.0)
Your touch end position is (195.5,374.0)
End location in image is (162.5,237.0)

Great! You’ve got the basic UI set up – now it’s time to make it dynamic.

UIDynamicAnimator and UIAttachmentBehavior

Note: If you skipped ahead from the previous section, download the starter project to continue from this point.

The first thing you want to do is make the image view move as you drag it. You will do this with a type of UIKit Dynamics class called a UIAttachmentBehavior.

Open ViewController.swift and place the following code in viewDidLoad(), below super.viewDidLoad().

animator = UIDynamicAnimator(referenceView: view)
originalBounds = imageView.bounds
originalCenter = imageView.center

The above code sets up a UIDynamicAnimator, which is UIKit’s engine for physics-based animation. You provide the view controller’s view as a reference view which defines the coordinate system for the animator.

You add behaviors to an animator, which allow you to do things like attaching views, pushing views, making them be affected by gravity, and more.

You’ll start with a UIAttachmentBehavior, to make the image view track your finger when you make a pan gesture.

To do this, add the following code to handleAttachmentGesture(sender:), underneath the two println statements in the case .Began: section:

// 1

// 2
let centerOffset = UIOffset(horizontal: boxLocation.x - imageView.bounds.midX,
                            vertical: boxLocation.y - imageView.bounds.midY)
attachmentBehavior = UIAttachmentBehavior(item: imageView,
    offsetFromCenter: centerOffset, attachedToAnchor: location)

// 3
redSquare.center = attachmentBehavior.anchorPoint
blueSquare.center = location

// 4

Let’s go over this section by section:

  1. First you remove any existing animation behaviors that might be hanging around.
  2. Next, you create a UIAttachmentBehavior that attaches the the point inside the image view where the user taps to an anchor point (which happens to be the exact same point). Later on, you will change the anchor point, which will cause the image view to move.

    Attaching an anchor point to a view is like installing an invisible rod that connects the anchor point to a fixed attachment position on the view.

  3. Update the red square to indicate the anchor point, and the blue square to indicate the point inside the image view that it is attached to. When the gesture starts, these will be the same point.
  4. Add this behavior to the animator to make it take effect.

Next you need to tell the anchor point itself to follow your finger. In handleAttachmentGesture(_:), replace the break statement in the default: case with the following code:

attachmentBehavior.anchorPoint = sender.locationInView(view)
redSquare.center = attachmentBehavior.anchorPoint

The default case handles the gesture update calls as the user pans around. The code here simply aligns the anchor point and red square to the finger’s current position. When the user’s finger moves, the gesture recognizer calls this method to update the anchor point to follow the touch. In addition, the animator automatically updates the view to follow the anchor point.

Build and run, and you are now able to drag the view around:

Dragged View

Notice how the view isn’t just translated around the screen; if you start the gesture in a corner of the image, the view will rotate as you move it because of the anchor point.

However it would be nice to return the view back to its original position when you’re done dragging. To fix this, add this new method to the class:

func resetDemo() {

  UIView.animateWithDuration(0.45) {
    self.imageView.bounds = self.originalBounds
    self.imageView.center = self.originalCenter
    self.imageView.transform = CGAffineTransformIdentity

Then call this in handleAttachmentGesture(_:), below the println calls in the .Ended: section:


Build and run, and now after you drag an image it should revert to its original position.


Next, you need to detach the view when you stop dragging, and endow it with momentum so that it can continue its trajectory when you release it while in motion. You will do this with a UIPushBehavior.

First, you’ll need two constants. Add these to the top of the file:

let ThrowingThreshold: CGFloat = 1000
let ThrowingVelocityPadding: CGFloat = 35

ThrowingThreshhold indicates how fast the view must be moving in order to have the view continue moving (versus immediately returning to its original spot). ThrowingVelocityPadding is a magic constant that affects how fast or slow the toss should be (this was chosen by trial and error).

Finally, inside handleAttachmentGesture(_:), replace the call to resetDemo() inside the .Ended case with the following:


// 1
let velocity = sender.velocityInView(view)
let magnitude = sqrt((velocity.x * velocity.x) + (velocity.y * velocity.y))

if magnitude > ThrowingThreshold {
  // 2
  let pushBehavior = UIPushBehavior(items: [imageView], mode: .Instantaneous)
  pushBehavior.pushDirection = CGVector(dx: velocity.x / 10, dy: velocity.y / 10)
  pushBehavior.magnitude = magnitude / ThrowingVelocityPadding

  self.pushBehavior = pushBehavior

  // 3
  let angle = Int(arc4random_uniform(20)) - 10

  itemBehavior = UIDynamicItemBehavior(items: [imageView])
  itemBehavior.friction = 0.2
  itemBehavior.allowsRotation = true
  itemBehavior.addAngularVelocity(CGFloat(angle), forItem: imageView)

  // 4
  let timeOffset = Int64(0.4 * Double(NSEC_PER_SEC))
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timeOffset), dispatch_get_main_queue()) {
} else {

Let’s go over this section by section:

  1. Ask the gesture for the velocity of the drag.

    Using velocity and your old friend the Pythagorean theorem, you compute the magnitude of the velocity — which is the hypotenuse of the triangle formed from the x direction velocity and the y direction velocity.

    To understand the theory behind this check out this Trigonometry for Game Programming tutorial.

  2. Assuming the gesture magnitude exceeds your minimum threshold set up for the action, you set up a push behavior.

    A push behavior applies a force to the specified items. In this case, it’s an instantaneous force against the image.

    The desired direction is composed of the x and y velocities converted to a vector that gives the directional portion. Once you have the push behavior set up, you add it to the animation sequence.

  3. This section sets up some rotations to make the image “fly away”. You can read up on the complicated math here.

    Some of this depends on how close to the edge your finger is when it initiates the gesture.

    Play around with the values here and watch how the movements change the effects. The values used give a nice, flowing rotation with a cool spinning effect!

  4. After a specified interval of time, the animation resets by sending the image back to its destination, so it zips off and returns to the screen — just like a ball bouncing off a wall!

Build and run, and you should now be able to toss your view offscreen in a pleasing manner!

Learn how to make tossable views with UIKit Dynamics!

Where To Go from Here?

Here is the final example project from this UIKit Dynamics tutorial.

Congratulations, you’ve now learned how to do some fancy UIKit dynamic animations that can give an app’s UI some pretty sweet effects.

If you want learn more about UIKit Dynamics, check out the two UIKit Dynamics chapters in iOS 7 by Tutorials.

Drop by the forums or leave a comment below to share your successes or ask questions about making cool animations in iOS. And use your new powers wisely!

Bjørn Olav Ruud

Bjørn is an iOS programmer from Norway. During the day he's a freelance iOS programmer and consultant. At night he experiments with Swift and games.

In his spare time Bjørn enjoys games (computer/card/board) for his mental health, and strength training, parkour and other activities that are likely to cause injury for his physical health.

Blog | GitHub | LinkedIn

Other Items of Interest

Save time.
Learn more with our video courses.

raywenderlich.com Weekly

Sign up to receive the latest tutorials from raywenderlich.com each week, and receive a free epic-length tutorial as a bonus!

Advertise with Us!

PragmaConf 2016 Come check out Alt U

Our Books

Our Team

Video Team

... 19 total!

Swift Team

... 15 total!

iOS Team

... 34 total!

Android Team

... 15 total!

macOS Team

... 11 total!

Apple Game Frameworks Team

... 12 total!

Unity Team

... 10 total!

Articles Team

... 11 total!

Resident Authors Team

... 15 total!