UIGestureRecognizer Tutorial: Getting Started

UIGestureRecognizer Tutorial: Getting Started

Learn how to use UIGestureRecognizers to pinch, zoom, drag, and more!

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.

[…]

Click here to download the starter project. Open it in Xcode and build and run.

[…]

Open up ViewController.swift and add the following function right below viewDidLoad() inside of the ViewController class:

[…]

So add the following to the bottom of the handlePan(recognizer:) function in ViewController.swift:

[…]

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.

[…]

Open up ViewController.swift. Below the ViewController class, create a ViewController class extension and adopt it to the UIGestureRecognizerDelegate as shown below:

[…]

To be able to play a sound, you’ll need to access the AVFoundation framework. At the top of Viewcontroller.swift, add:

Add the following changes to ViewController.swift just before viewDidLoad():

[…]

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:

[…]

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:

[…]

OK, now to use this new recognizer! Open ViewController.swift and make the following changes.

[…]