UIKit Dynamics and Swift Tutorial: Tossing Views
Learn how to toss your views around with gestures and realistic physics behavior in this UIKit Dynamics tutorial! By Bjørn Olav Ruud.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
UIKit Dynamics and Swift Tutorial: Tossing Views
15 mins
UIPushBehavior
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:
animator.removeAllBehaviors()
// 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
animator.addBehavior(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)
animator.addBehavior(itemBehavior)
// 4
let timeOffset = Int64(0.4 * Double(NSEC_PER_SEC))
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, timeOffset), dispatch_get_main_queue()) {
self.resetDemo()
}
} else {
resetDemo()
}
Let’s go over this section by section:
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.
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.
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!
- Ask the gesture for the velocity of the drag.
- Assuming the gesture magnitude exceeds your minimum threshold set up for the action, you set up a push behavior.
- This section sets up some rotations to make the image “fly away”. You can read up on the complicated math here.
- 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!
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!