Update note: This tutorial has been updated to Xcode 9, Swift 4, and iOS 11 by Brody Eller. The original tutorial was written by Caroline Begbie.
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! :]
Getting Started
Click here to download the starter project. Open it in Xcode and build and run.
You should see the following on your device or simulator:
UIGestureRecognizer Overview
Before you get started, here’s a brief overview of how you use UIGestureRecognizer
s and why they’re so handy.
In the old days before UIGestureRecognizer
s, 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, if your app requires them.
Using UIGestureRecognizer
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.
UIPanGestureRecognizer
Open up Main.storyboard. Inside the Object Library, look for the Pan Gesture Recognizer object. Then drag the Pan Gesture Recognizer object onto 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.
The starter project has connected the monkey Image View with the Pinch Gesture Recognizer and Rotation Gesture Recognizer for you. It has also connected the banana Image View with the Pan Gesture Recognizer, Pinch Gesture Recognizer, and Rotation Gesture Recognizer for you. These connections from the starter project are achieved by dragging a gesture recognizer on top of an image view as shown earlier.
You may wonder why the UIGestureRecognizer
is associated with 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 right below viewDidLoad()
inside of the ViewController
class:
@IBAction func handlePan(recognizer:UIPanGestureRecognizer) {
let translation = recognizer.translation(in: self.view)
if let view = recognizer.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
recognizer.setTranslation(CGPoint.zero, in: 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 translation(in:)
function. Here you use that amount to move the center of the monkey the same amount the finger has been dragged.
It’s 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(recognizer:)
.
At this point your Connections Inspector for the Pan Gesture Recognizer should look like this:
One more thing: If you compile and run, and try to drag the monkey, it won’t 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.
The starter project has attached a Pan Gesture Recognizer to the banana Image View for you. This is achieved using the same method as attaching a Pan Gesture Recognizer to the monkey Image View as shown earlier.
Now connect the handlePan(recognizer:)
callback function to the banana Image View by performing the following:
- Control drag from the banana Pan Gesture Recognizer to the View Controller and select
handlePan:
. - Make sure User Interaction Enabled is checked on the banana as well.
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
velocity(in:)
that you can use in the UIPanGestureRecognizer!
So add the following to the bottom of the handlePan(recognizer:)
function in ViewController.swift:
if recognizer.state == UIGestureRecognizerState.ended {
// 1
let velocity = recognizer.velocity(in: self.view)
let magnitude = sqrt((velocity.x * velocity.x) + (velocity.y * velocity.y))
let slideMultiplier = magnitude / 200
print("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.animate(withDuration: Double(slideFactor * 2),
delay: 0,
// 6
options: UIViewAnimationOptions.curveEaseOut,
animations: {recognizer.view!.center = finalPoint },
completion: nil)
}
This simple deceleration function uses 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!
The starter project has created the handlePinch(recognizer:)
and the handleRotate(recognizer:)
callback functions for you. It has also connected the callback functions to the monkey Image View and the banana Image View.
Open up ViewController.swift. Add the following to handlePinch(recognizer:)
:
if let view = recognizer.view {
view.transform = view.transform.scaledBy(x: recognizer.scale, y: recognizer.scale)
recognizer.scale = 1
}
Next add the following to handleRotate(recognizer:)
:
if let view = recognizer.view {
view.transform = view.transform.rotated(by: 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 CGAffineTransform(scaleX:y:)
to scale a given transform and CGAffineTransform(rotationAngle:)
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:
- In the same way that you did previously, connect the two Pinch Gesture Recognizers to the View Controller’s
handlePinch(recognizer:)
function. - Connect the two Rotation Gesture Recognizers to the View Controller’s
handleRotate(recognizer:)
function.
Your View Controller connections should now look like this:
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 option key and drag to simulate two fingers, and hold down shift and option 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!
Note: There seems to be a bug with the Xcode 9 Simulator. If you’re experiencing issues with pinch and rotation gestures on the Xcode 9 Simulator, try running on a device instead.
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. Below the ViewController
class, create a ViewController
class extension and adopt it to the UIGestureRecognizerDelegate
as shown below:
extension ViewController: UIGestureRecognizerDelegate {
}
Then implement one of the delegate’s optional functions:
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: 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 (6 gesture recognizers in total).
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: String) -> AVAudioPlayer {
let url = Bundle.main.url(forResource: filename, withExtension: "caf")
var player = AVAudioPlayer()
do {
try player = AVAudioPlayer(contentsOf: url!)
player.prepareToPlay()
} catch {
print("Error loading \(url!): \(error.localizedDescription)")
}
return player
}
Replace viewDidLoad()
with the following:
super.viewDidLoad()
//1
let filteredSubviews = self.view.subviews.filter({
$0 is UIImageView })
//2
for view in filteredSubviews {
//3
let recognizer = UITapGestureRecognizer(target: self,
action:#selector(handleTap(recognizer:)))
//4
recognizer.delegate = self
view.addGestureRecognizer(recognizer)
//TODO: Add a custom gesture recognizer too
}
self.chompPlayer = self.loadSound(filename: "chomp")
The starter project has created the handleTap(recognizer:)
callback function. The starter project has also connected the callback function to the monkey Image View and the banana Image View for you. Add the following inside of handleTap(recognizer:)
:
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. This is an alternative way of adding gesture recognizers. Previously you added the recognizers to the storyboard. - 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 require(toFail:)
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.
Add these two lines to viewDidLoad()
, right before the TODO:
recognizer.require(toFail: monkeyPan)
recognizer.require(toFail: 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 = CGPoint.zero
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 anInt
, but you need to specifydistanceForTickleGesture
as aCGFloat
. If you do not, then it will be inferred as aDouble
, and cause difficulties when doing calculations withCGPoint
s 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: Set<UITouch>, with event: UIEvent) {
if let touch = touches.first {
self.curTickleStart = touch.location(in: self.view)
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent) {
if let touch = touches.first {
let ticklePoint = touch.location(in: 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 += 1
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 = CGPoint.zero
self.lastDirection = .DirectionUnknown
if self.state == .possible {
self.state = .failed
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent) {
self.reset()
}
override func touchesCancelled(_ touches: Set<UITouch>, with 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(_:with:)
, touchesMoved(_:with:)
, touchesEnded(_:with:)
, and touchesCancelled(_:with:)
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(recognizer:)))
recognizer2.delegate = self
view.addGestureRecognizer(recognizer2)
At end of viewDidLoad()
add:
self.hehePlayer = self.loadSound(filename: "hehehe1")
Finally, create a new method at the end of the class:
@objc 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!
The post UIGestureRecognizer Tutorial: Getting Started appeared first on Ray Wenderlich.