Update note: This tutorial was fully updated for iOS 8 and Swift by Caroline Begbie. Original post by Ray Wenderlich.
Update 12/10/14: Updated for Xcode 6.1.1.
If you need to detect gestures in your app, such as taps, pinches, pans, or rotations, it’s extremely easy with Swift and the built-in UIGestureRecognizer classes.
In this tutorial, you’ll learn how you can easily add gesture recognizers into your app, both within the Storyboard editor in Xcode, and programatically. You’ll create a simple app where you can move a monkey and a banana around by dragging, pinching, and rotating with the help of gesture recognizers.
You’ll also try out some cool extras like:
- Adding deceleration for movement
- Setting dependencies between gesture recognizers
- Creating a custom UIGestureRecognizer so you can tickle the monkey!
This tutorial assumes you are familiar with the basic concepts of Storyboards. If you are new to them, you may wish to check out our Storyboard tutorials first.
I think the monkey just gave us the thumbs up gesture, so let’s get started! :]
Note: At the time of writing this tutorial, our understanding is we cannot post screenshots of Xcode 6 since it is still in beta. Therefore, we are suppressing screenshots in this Swift tutorial until we are sure it is OK.
Getting Started
Open up Xcode 6 and create a new project with the iOS\Application\Single View Application template. For the Product Name enter MonkeyPinch, for the Language choose Swift, and for the Devices choose iPhone. Click Next, choose the folder to save your project, and click Create.
Before you go any further, download the resources for this project and drag the six files into your project. Tick Destination: Copy items if needed, choose Create groups, and click Finish.
Next, open up Main.storyboard. View controllers are now square by default, so that you can use just one storyboard for multiple devices. Generally you will layout your storyboards using constraints and size classes. But because this app is only going to be for the iPhone, you can disable size classes. On the File Inspector panel (View Menu > Utilities > Show File Inspector), untick Use Size Classes. Choose Keep size class data for: iPhone, and click Disable Size Classes.
Your view will now reflect the size and proportions of the iPhone 5.
Drag an Image View into the View Controller. Set the image to monkey.png, and resize the Image View to match the size of the image itself by selecting Editor Menu > Size to Fit Content. Then drag a second image view in, set it to banana.png, and also resize it. Arrange the image views however you like in the view controller. At this point you should have something like this:
Arrange the image views within the view.
That’s it for the UI for this app – now you’ll add a gesture recognizer so you can drag those image views around!
UIGestureRecognizer Overview
Before you get started, here’s a brief overview of how you use UIGestureRecognizers and why they’re so handy.
In the old days before UIGestureRecognizers, if you wanted to detect a gesture such as a swipe, you’d have to register for notifications on every touch within a UIView – such as touchesBegan, touchesMoves, and touchesEnded. Each programmer wrote slightly different code to detect touches, resulting in subtle bugs and inconsistencies across apps.
In iOS 3.0, Apple came to the rescue with UIGestureRecognizer classes! These provide a default implementation of detecting common gestures such as taps, pinches, rotations, swipes, pans, and long presses. By using them, not only does it save you a ton of code, but it makes your apps work properly too! Of course you can still use the old touch notifications instead, if your app requires them.
Using UIGestureRecognizers is extremely simple. You just perform the following steps:
- Create a gesture recognizer. When you create a gesture recognizer, you specify a callback function so the gesture recognizer can send you updates when the gesture starts, changes, or ends.
- Add the gesture recognizer to a view. Each gesture recognizer is associated with one (and only one) view. When a touch occurs within the bounds of that view, the gesture recognizer will look to see if it matches the type of touch it’s looking for, and if a match is found it will notify the callback function.
You can perform these two steps programatically (which you’ll do later on in this tutorial), but it’s even easier adding a gesture recognizer visually with the Storyboard editor. So now to add your first gesture recognizer into this project!
UIPanGestureRecognizer
Still with Main.storyboard open, look inside the Object Library for the Pan Gesture Recognizer, and drag it on top of the monkey Image View. This both creates the pan gesture recognizer, and associates it with the monkey Image View. You can verify you got it connected OK by clicking on the monkey Image View, looking at the Connections Inspector (View Menu > Utilities > Show Connections Inspector), and making sure the Pan Gesture Recognizer is in the gestureRecognizers Outlet Collection.
You may wonder why you associated it to the image view instead of the view itself. Either approach would be OK, it’s just what makes most sense for your project. Since you tied it to the monkey, you know that any touches are within the bounds of the monkey so you’re good to go. The drawback of this method is sometimes you might want touches to be able to extend beyond the bounds. In that case, you could add the gesture recognizer to the view itself, but you’d have to write code to check if the user is touching within the bounds of the monkey or the banana and react accordingly.
Now that you’ve created the pan gesture recognizer and associated it to the image view, you just have to write the callback function so something actually happens when the pan occurs.
Open up ViewController.swift and add the following function at the end of the ViewController class:
@IBAction func handlePan(recognizer:UIPanGestureRecognizer) { let translation = recognizer.translationInView(self.view) recognizer.view!.center = CGPoint(x:recognizer.view!.center.x + translation.x, y:recognizer.view!.center.y + translation.y) recognizer.setTranslation(CGPointZero, inView: self.view) }
The UIPanGestureRecognizer will call this function when a pan gesture is first detected, and then continuously as the user continues to pan, and one last time when the pan is complete (usually the user lifting their finger).
The UIPanGestureRecognizer passes itself as an argument to this function. You can retrieve the amount the user has moved their finger by calling the translationInView: function. Here you use that amount to move the center of the monkey the same amount the finger has been dragged.
It’s extremely important to set the translation back to zero once you are done. Otherwise, the translation will keep compounding each time, and you’ll see your monkey rapidly move off the screen!
Note that instead of hard-coding the monkey image view into this function, you get a reference to the monkey image view by calling recognizer.view. This makes your code more generic, so that you can re-use this same routine for the banana image view later on.
OK, now that this function is complete, you will hook it up to the UIPanGestureRecognizer. In Main.storyboard, control drag from the Pan Gesture Recognizer to View Controller. A popup will appear – select handlePan:.
One more thing. If you compile and run, and try to drag the monkey, it will not work yet. The reason is that touches are disabled by default on views that normally don’t accept touches, like Image Views. So select both image views, open up the Attributes Inspector, and check the User Interaction Enabled checkbox.
Compile and run again, and this time you should be able to drag the monkey around the screen!
Note that you can’t drag the banana. This is because gesture recognizers should be tied to one (and only one) view. So go ahead and add another gesture recognizer for the banana, by performing the following steps:
- Drag a Pan Gesture Recognizer on top of the banana Image View.
- Control drag from the new Pan Gesture Recognizer to the View Controller and connect it to the handlePan: function.
Give it a try and you should now be able to drag both image views across the screen. Pretty easy to implement such a cool and fun effect, eh?
Gratuitous Deceleration
In a lot of Apple apps and controls, when you stop moving something there’s a bit of deceleration as it finishes moving. Think about scrolling a web view, for example. It’s common to want to have this type of behavior in your apps.
There are many ways of doing this, but you’re going to do one very simple implementation for a rough but nice effect. The idea is to detect when the gesture ends, figure out how fast the touch was moving, and animate the object moving to a final destination based on the touch speed.
- To detect when the gesture ends: The callback passed to the gesture recognizer is called potentially multiple times – when the gesture recognizer changes its state to began, changed, or ended for example. You can find out what state the gesture recognizer is in simply by looking at its state property.
- To detect the touch velocity: Some gesture recognizers return additional information – you can look at the API guide to see what you can get. There’s a handy function called velocityInView that you can use in the UIPanGestureRecognizer!
So add the following to the bottom of the handlePan: function in ViewController.swift:
if recognizer.state == UIGestureRecognizerState.Ended { // 1 let velocity = recognizer.velocityInView(self.view) let magnitude = sqrt((velocity.x * velocity.x) + (velocity.y * velocity.y)) let slideMultiplier = magnitude / 200 println("magnitude: \(magnitude), slideMultiplier: \(slideMultiplier)") // 2 let slideFactor = 0.1 * slideMultiplier //Increase for more of a slide // 3 var finalPoint = CGPoint(x:recognizer.view!.center.x + (velocity.x * slideFactor), y:recognizer.view!.center.y + (velocity.y * slideFactor)) // 4 finalPoint.x = min(max(finalPoint.x, 0), self.view.bounds.size.width) finalPoint.y = min(max(finalPoint.y, 0), self.view.bounds.size.height) // 5 UIView.animateWithDuration(Double(slideFactor * 2), delay: 0, // 6 options: UIViewAnimationOptions.CurveEaseOut, animations: {recognizer.view!.center = finalPoint }, completion: nil) }
This is just a very simple function I wrote up for this tutorial to simulate deceleration. It takes the following strategy:
- Figure out the length of the velocity vector (i.e. the magnitude)
- If the length is < 200, then decrease the base speed, otherwise increase it.
- Calculate a final point based on the velocity and the slideFactor.
- Make sure the final point is within the view’s bounds
- Animate the view to the final resting place.
- Use the “ease out” animation option to slow down the movement over time.
Compile and run to try it out, you should now have some basic but nice deceleration! Feel free to play around with it and improve it – if you come up with a better implementation, please share in the forum discussion at the end of this article.
Pinch and Rotation Gestures
Your app is coming along great so far, but it would be even cooler if you could scale and rotate the image views by using pinch and rotation gestures as well!
First, add the code for the callbacks. Add the following functions to ViewController.swift at the end of the ViewController class:
@IBAction func handlePinch(recognizer : UIPinchGestureRecognizer) { recognizer.view!.transform = CGAffineTransformScale(recognizer.view!.transform, recognizer.scale, recognizer.scale) recognizer.scale = 1 } @IBAction func handleRotate(recognizer : UIRotationGestureRecognizer) { recognizer.view!.transform = CGAffineTransformRotate(recognizer.view!.transform, recognizer.rotation) recognizer.rotation = 0 }
Just like you could get the translation from the UIPanGestureRecognizer, you can get the scale and rotation from the UIPinchGestureRecognizer and UIRotationGestureRecognizer.
Every view has a transform that is applied to it, which you can think of as information on the rotation, scale, and translation that should be applied to the view. Apple has a lot of built in functions to make working with a transform easy, such as CGAffineTransformScale (to scale a given transform) and CGAffineTransformRotate (to rotate a given transform). Here you will use these to update the view’s transform based on the gesture.
Again, since you’re updating the view each time the gesture updates, it’s very important to reset the scale and rotation back to the default state so you don’t have craziness going on.
Now hook these up in the Storyboard editor. Open up Main.storyboard and perform the following steps:
- Drag a Pinch Gesture Recognizer and a Rotation Gesture Recognizer on top of the monkey. Then repeat this for the banana.
- In the same way that you did previously, connect the Pinch Gesture Recognizers to the View Controller’s handlePinch: function.
- Connect the Rotation Gesture recognizers to the View Controller’s handleRotate: function.
Build and run. Run it on a device if possible, because pinches and rotations are kinda hard to do on the simulator. If you are running on the simulator, hold down the alt key and drag to simulate two fingers, and hold down shift and alt at the same time to move the simulated fingers together to a different position. Now you should be able to scale and rotate the monkey and banana!
Pinch to zoom, and drag the objects around in the running app!
Simultaneous Gesture Recognizers
You may notice that if you put one finger on the monkey, and one on the banana, you can drag them around at the same time. Kinda cool, eh?
However, you’ll notice that if you try to drag the monkey around, and in the middle of dragging bring down a second finger to attempt to pinch to zoom, it doesn’t work. By default, once one gesture recognizer on a view “claims” the gesture, no others can recognize a gesture from that point on.
However, you can change this by overriding a function in the UIGestureRecognizer delegate.
Open up ViewController.swift and mark the class as implementing UIGestureRecognizerDelegate as shown below:
class ViewController: UIViewController, UIGestureRecognizerDelegate {
Then implement one of the delegate’s optional functions:
func gestureRecognizer(UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer:UIGestureRecognizer) -> Bool { return true }
This function tells the gesture recognizer whether it is OK to recognize a gesture if another (given) recognizer has already detected a gesture. The default implementation always returns false – here you switch it to always return true.
Next, open Main.storyboard, and for each gesture recognizer connect its delegate outlet to the view controller.
Build and run the app again, and now you should be able to drag the monkey, pinch to scale it, and continue dragging afterwards! You can even scale and rotate at the same time in a natural way. This makes for a much nicer experience for the user.
Programmatic UIGestureRecognizers
So far you’ve created gesture recognizers with the Storyboard editor, but what if you wanted to do things programatically?
It’s just as easy, so you’ll try it out by adding a tap gesture recognizer to play a sound effect when either of these image views are tapped.
To be able to play a sound, you’ll need to access the AVFoundation framework. At the top of Viewcontroller.swift, add:
import AVFoundation
Add the following changes to ViewController.swift just before viewDidLoad:
var chompPlayer:AVAudioPlayer? = nil func loadSound(filename:NSString) -> AVAudioPlayer { let url = NSBundle.mainBundle().URLForResource(filename, withExtension: "caf") var error:NSError? = nil let player = AVAudioPlayer(contentsOfURL: url, error: &error) if error != nil { println("Error loading \(url): \(error?.localizedDescription)") } else { player.prepareToPlay() } return player }
Replace viewDidLoad with the following:
override func viewDidLoad() { super.viewDidLoad() //1 let filteredSubviews = self.view.subviews.filter({ $0.isKindOfClass(UIImageView) }) // 2 for view in filteredSubviews { // 3 let recognizer = UITapGestureRecognizer(target: self, action:Selector("handleTap:")) // 4 recognizer.delegate = self view.addGestureRecognizer(recognizer) //TODO: Add a custom gesture recognizer too } self.chompPlayer = self.loadSound("chomp") }
Add to the bottom of the ViewController class:
func handleTap(recognizer: UITapGestureRecognizer) { self.chompPlayer?.play() }
The audio playing code is outside of the scope of this tutorial so I won’t discuss it (although it is incredibly simple).
The important part is in viewDidLoad:
- Create a filtered array of just the monkey and banana image views
- Cycle through the filtered array.
- Create a UITapGestureRecognizer for each image view, specifying the callback.
- Set the delegate of the recognizer programatically, and add the recognizer to the image view.
That’s it! Compile and run, and now you should be able to tap the image views for a sound effect!
UIGestureRecognizer Dependencies
It works pretty well, except there’s one minor annoyance. If you drag an object a very slight amount, it will pan it and play the sound effect. But what you really want is to only play the sound effect if no pan occurs.
To solve this you could remove or modify the delegate callback to behave differently in the case a touch and pinch coincide, but here is another useful thing you can do with gesture recognizers: setting dependencies.
There’s a function called requireGestureRecognizerToFail: that you can call on a gesture recognizer. Can you guess what it does? ;]
Open Main.storyboard, open up the Assistant Editor, and make sure that ViewController.swift is showing there. Then control-drag from the monkey pan gesture recognizer to below the class declaration, and connect it to an outlet named monkeyPan. Repeat this for the banana pan gesture recognizer, but name the outlet bananaPan.
Then simply add these two lines to viewDidLoad, right before the TODO:
recognizer.requireGestureRecognizerToFail(monkeyPan) recognizer.requireGestureRecognizerToFail(bananaPan)
Now the tap gesture recognizer will only get called if no pan is detected. Pretty cool eh? You might find this technique useful in some of your projects.
Custom UIGestureRecognizer
At this point you know pretty much everything you need to know to use the built-in gesture recognizers in your apps. But what if you want to detect some kind of gesture not supported by the built-in recognizers?
Well, you could always write your own! Now you’ll try it out by writing a very simple gesture recognizer to detect if you try to “tickle” the monkey or banana by moving your finger several times from left to right.
Create a new file with the iOS\Source\Swift File template. Name the file TickleGestureRecognizer.
Then replace the contents of TickleGestureRecognizer.swift with the following:
import UIKit class TickleGestureRecognizer:UIGestureRecognizer { // 1 let requiredTickles = 2 let distanceForTickleGesture:CGFloat = 25.0 // 2 enum Direction:Int { case DirectionUnknown = 0 case DirectionLeft case DirectionRight } // 3 var tickleCount:Int = 0 var curTickleStart:CGPoint = CGPointZero var lastDirection:Direction = .DirectionUnknown }
This is what you just declared step by step:
- These are the constants that define what the gesture will need. Note that requiredTickles will be inferred as an Int, but you need to specify distanceForTickleGesture as a CGFloat. If you do not, then it will be inferred as a Double, and cause difficulties when doing calculations with CGPoints later on.
- These are the possible tickle directions.
- Here are the three variables to keep track of to detect this gesture:
- tickleCount: How many times the user has switched the direction of their finger (while moving a minimum amount of points). Once the user moves their finger direction three times, you count it as a tickle gesture.
- curTickleStart: The point where the user started moving in this tickle. You’ll update this each time the user switches direction (while moving a minimum amount of points).
- lastDirection: The last direction the finger was moving. It will start out as unknown, and after the user moves a minimum amount you’ll check whether they’ve gone left or right and update this appropriately.
Of course, these properties here are specific to the gesture you’re detecting here – you’ll have your own if you’re making a recognizer for a different type of gesture, but you can get the general idea here.
One of the things that you’ll be changing is the state of the gesture – when a tickle is completed, you’ll need to change the state of the gesture to ended. In the original Objective-C UIGestureRecognizer, state is a read-only property, so you will need to create a Bridging Header to be able to redeclare this property.
The easiest way to do this is to create an Objective-C Class, and then delete the implementation part.
Create a new file, using the iOS\Source\Objective-C File template. Call the file Bridging-Header, and click Create. You will then be asked whether you would like to configure an Objective-C bridging header. Choose Yes. Two new files will be added to your project:
- MonkeyPinch-Bridging-Header.h
- Bridging-Header.m
Delete Bridging-Header.m.
Add this Objective-C code to MonkeyPinch-Bridging-Header.h:
#import <UIKit/UIGestureRecognizerSubclass.h>
Now you will be able to change the UIGestureRecognizer’s state property in TickleGestureRecognizer.swift.
Switch to TickleGestureRecognizer.swift and add the following functions to the class:
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) { let touch = touches.anyObject() as UITouch self.curTickleStart = touch.locationInView(self.view) } override func touchesMoved(touches: NSSet!, withEvent event: UIEvent!) { let touch = touches.anyObject() as UITouch let ticklePoint = touch.locationInView(self.view) let moveAmt = ticklePoint.x - curTickleStart.x var curDirection:Direction if moveAmt < 0 { curDirection = .DirectionLeft } else { curDirection = .DirectionRight } //moveAmt is a Float, so self.distanceForTickleGesture needs to be a Float also if abs(moveAmt) < self.distanceForTickleGesture { return } if self.lastDirection == .DirectionUnknown || (self.lastDirection == .DirectionLeft && curDirection == .DirectionRight) || (self.lastDirection == .DirectionRight && curDirection == .DirectionLeft) { self.tickleCount++ self.curTickleStart = ticklePoint self.lastDirection = curDirection if self.state == .Possible && self.tickleCount > self.requiredTickles { self.state = .Ended } } } override func reset() { self.tickleCount = 0 self.curTickleStart = CGPointZero self.lastDirection = .DirectionUnknown if self.state == .Possible { self.state = .Failed } } override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) { self.reset() } override func touchesCancelled(touches: NSSet!, withEvent event: UIEvent!) { self.reset() }
There’s a lot of code here, but I’m not going to go over the specifics because frankly they’re not quite important. The important part is the general idea of how it works: you’re overriding the UIGestureRecognizer’s touchesBegan, touchesMoved, touchesEnded, and touchesCancelled functions, and writing custom code to look at the touches and detect the gesture.
Once you’ve found the gesture, you want to send updates to the callback function. You do this by changing the state property of the gesture recognizer. Usually once the gesture begins, you want to set the state to .Began, send any updates with .Changed, and finalize it with .Ended.
But for this simple gesture recognizer, once the user has tickled the object, that’s it – you just mark it as ended. The callback you will add to ViewController.swift will get called and you can implement the code there.
OK, now to use this new recognizer! Open ViewController.swift and make the following changes.
Add to the top of the class:
var hehePlayer:AVAudioPlayer? = nil
In viewDidLoad, right after TODO, add:
let recognizer2 = TickleGestureRecognizer(target: self, action: Selector("handleTickle:")) recognizer2.delegate = self view.addGestureRecognizer(recognizer2)
At end of viewDidLoad add:
self.hehePlayer = self.loadSound("hehehe1")
Add at the beginning of handlePan: (gotta turn off pan to recognize tickles):
//comment for panning //uncomment for tickling return;
At the end of the class add the callback:
func handleTickle(recognizer:TickleGestureRecognizer) { self.hehePlayer?.play() }
So you can see that using this custom gesture recognizer is as simple as using the built-in ones!
Compile and run and “he he, that tickles!”
Where To Go From Here?
Here’s the download for the final project with all of the code from the above tutorial.
Congrats, you’re now a master of gesture recognizers, both built-in and your own custom ones! Touch interaction is such an important part of iOS devices and UIGestureRecognizer is the key to easy-to-use gestures beyond simple button taps.
If you have any comments or questions about this tutorial or gesture recognizers in general, please join the forum discussion below!
Credits: Artwork by Vicki Wenderlich of Game Art Guppy – Game Art Resources for Indie Game Developers.