Detect and respond to Touch Gestures in Swift

Touch gestures give commands to an app without placing an object on the user interface such as a button. Gestures can often work with one or more fingertips that you can define using either the Attributes Inspector pane or through Swift code.

The different types of touch gestures that an iOS app can detect and respond to include

  • Tap - A fingertip touches the screen and lifts up.
  • Pinch - Two fingertips come together or move apart.
  • Rotation - Two fingertips rotate left or right in a circular motion.
  • Pan - A fingertip slides in a dragging motion across the screen.
  • Swipe - A fingertip slides up, down, left, or right across the screen and lifts up.
  • Screen edge pan - A fingertip slides in a dragging motion that starts near the edge of the screen.
  • Long press - A fingertip touches and presses down on the screen.

You can create touch gestures on an app’s user interface solely through Swift code or by placing gesture recognizer objects on a view from the Object Library.

To detect gestures in an app, you need to do the following:

  • Add a gesture recognizer to a view.
  • Create an IBAction method to respond to the gesture.
  • Define which object needs to respond to the gesture.

Detecting Tap Gestures

Tap gestures simply detect when a user taps on the screen. By default, a tap gesture recognizes a single tap by one fingertip, but you can define multiple taps by two or more fingertips.

To see how to detect tap gestures, follow these steps:

  1. Click the Main.storyboard file in the Navigator pane. Xcode displays the single view.
  2. Click the Library icon to open the Object Library window and look for the Tap Gesture Recognizer.
  3. Drag and drop a Tap Gesture Recognizer anywhere on the view. Notice that a gesture recognizer doesn’t appear directly on the view but appears at the top of the view and in the Document Outline.
  4. Click the Tap Gesture Recognizer in the Document Outline.
  5. Click the Attributes Inspector icon in the upper right corner of the Xcode window. Notice that the Attributes Inspector lets you define how many taps and touches (fingertips) needed to recognize a tap gesture. By default, a tap gesture only requires 1 tap with 1 touch (fingertip).
  6. Click the Library icon to open the Object Library window and drag and drop two labels anywhere on the view.
  7. Double-click one label and type Visual Solution and press ENTER.
  8. Double-click the other label and type Programmatic Solution and press ENTER.
  9. Choose Editor > Resolve Auto Layout Issues > Reset to Suggested Constraints at the bottom half of the submenu. Xcode adds constraints to both labels.
  10. Click the Visual Solution label and click the Attributes Inspector icon in the upper right corner of the Xcode window.
  11. Select the User Interaction Enabled check box. With User Interaction Enabled selected, the label can respond to the user touching it.
  12. Move the mouse pointer over the Visual Solution label, hold down the Control key, and Ctrl-drag from the label to the Tap Gesture Recognizer in the Document Outline or above the View Controller
  13. Release the Control key and the left mouse button. A popup menu appears.
  14. Click gestureRecognizers.
  15. Click the Collections Inspector icon in the upper right corner of the Xcode window. The Connections Inspector pane shows that the label is linked to the Tap Gesture Recognizer, which means only the label can respond to tap gestures.
  16. Click the Assistant Editor icon in the upper right corner of the Xcode window.
  17. Move the mouse pointer over the Tap Gesture Recognizer icon in the Document Outline or at the top of the View Controller, hold down the Control key, and Ctrl-drag above the last curly bracket at the bottom of the ViewController.swift file.
  18. Release the Control key and the left mouse button. A popup window appears.
  19. Click in the Name text field and type tapDetected, click the Type popup menu and choose UITapGestureRecognizer, and click the Connect button. Xcode creates an IBAction method.
  20. Modify this tapDetected IBAction method as follows:
@IBAction func tapDetected(_ sender: UITapGestureRecognizer) { 
    print ("Tap detected")
}

We can also define gesture recognizers solely through Swift code, which we’ll do with the Programmatic Solution label.

  1. Click the Main.storyboard file in the Navigator pane. Xcode displays the single view.
  2. Click the Assistant Editor icon in the upper right corner of the Xcode window. Xcode displays the Main.storyboard and ViewController.swift files side by side.
  3. Move the mouse pointer over the Programmatic Solution label, hold down the Control key, and Ctrl-drag from the label underneath the class ViewController line in the ViewController. swift file.
  4. Release the Control key and the left mouse button. A popup window appears.
  5. Click in the Name text field, type labelCode, and click the Connect button. Xcode creates an IBOutlet as follows:
@IBOutlet var labelCode: UILabel!

Edit the viewDidLoad method as follows:

override func viewDidLoad() {
    super.viewDidLoad() 
    labelCode.isUserInteractionEnabled = true
    let tapGesture = UITapGestureRecognizer(target: self,
        action: #selector(handleTap)) 
    labelCode.addGestureRecognizer(tapGesture)
}

Instead of selecting the User Interaction Enabled check box in the Attributes Inspector pane, we can simply set the .isUserInteractionEnabled property to true for the second label that displays Programmatic Solution.

Rather than drag and drop a Tap Gesture Recognizer from the Object Library onto the view, we can create a UITapGestureRecognizer using Swift code. This means we also need to define a function to respond to the tap gesture, which is defined by #selector(handleTap). Finally, we need to add this tap gesture to the label instead of linking it through the Connections Inspector pane.

Add the following underneath the viewDidLoad method:

@objc func handleTap() {
    print ("Tap on second label detected")
}

When customizing a tap gesture using Swift code, you can define the following two properties:

  • .numberOfTapsRequired – Defines how many taps needed to recognize a tap gesture such as one tap (default)
  • .numberOfTouchesRequired – Defines how many fingertips (touches) are needed to recognize a tap gesture

Detecting Pinch Gestures

A pinch gesture occurs when two fingertips either move toward each other or move away from each other. During a pinch gesture, an app can recognize scale and velocity. The scale defines the relative position of the two fingertips, while velocity detects the speed of the pinching motion.

To see how to detect a pinch gesture, follow these steps:

  1. Click the Main.storyboard file in the Navigator pane. Xcode displays the single view.
  2. Click the Library icon to open the Object Library window and look for the Pinch Gesture Recognizer.
  3. Drag and drop the Pinch Gesture Recognizer onto the view. Xcode displays the Pinch Gesture Recognizer in the Document Outline and above the View Controller.
  4. Click the Library icon to open the Object Library window and drag and drop an image view in the center of the user interface.
  5. Click the Attributes Inspector icon in the upper right corner of the Xcode window.
  6. Click in the Background popup menu and choose green color.
  7. Select the User Interaction Enabled check box. This allows the image view to respond to the user.
  8. Click the Align icon in the bottom of the middle Xcode pane. A window appears.
  9. Select the Horizontally in Container and Vertically in Container check boxes and then click the Add 2 Constraints button.
  10. Move the mouse pointer over the image view, hold down the Control key, and Ctrl-drag from the image view to the Pinch Gesture Recognizer icon in the Document Outline or at the top of the View Controller.
  11. Release the Control key and the left mouse button. A window appears.
  12. Choose gestureRecognizers. This link lets the image view detect pinch gestures.
  13. Click the Assistant Editor icon. Xcode displays the Main.storyboard and ViewController.swift file side by side.
  14. Move the mouse pointer over the image view, hold down the Control key, and Ctrl-drag from the image view to the ViewController.swift file underneath the IBOutlet line.
  15. Release the Control key and the left mouse button. A popup window appears.
  16. Click in the Name text field, type topImageView, and click the Connect button.
  17. Move the mouse pointer over the Pinch Gesture Recognizer icon in the Document Outline or at the top of the View Controller, hold down the Control key, and Ctrl-drag from the Pinch Gesture Recognizer above the last curly bracket in the ViewController.swift file.
  18. Release the Control key and the left mouse button. A popup window appears.
  19. Click in the Name text field, type pinchDetected, click in the Type popup menu and choose UIPinchGestureRecognizer, and click the Connect button. Xcode creates an IBAction method.
  20. Edit the pinchDetected IBAction method as follows:
@IBAction func pinchDetected(_ sender: UIPinchGestureRecognizer) { 
    topImageView.transform = CGAffineTransform(scaleX: sender. scale, y: sender.scale)
}

Let’s see how to duplicate this process through Swift code alone.

import UIKit
class ViewController: UIViewController {
    @IBOutlet var topImageView: UIImageView! 
    var pinchMe: UIPinchGestureRecognizer?

    override func viewDidLoad() {
        super.viewDidLoad()
        topImageView.isUserInteractionEnabled = true 
        topImageView.backgroundColor = UIColor.green
        let pinchGesture = UIPinchGestureRecognizer(target: self, 
            action: #selector(handlePinch)) topImageView.addGestureRecognizer(pinchGesture)
        pinchMe = pinchGesture
    }

    @objc func handlePinch() {
        topImageView.transform = CGAffineTransform(scaleX: pinchMe!.scale, y: pinchMe!.scale)
    } 
}

Detecting Rotation Gestures

A rotation gesture is similar to a pinch gesture because they both use two fingertips. The main difference is that rotation gesture detects when the two fingertips move in a circular motion clockwise or counterclockwise. During a rotation gesture, an app can recognize rotation (measured in radians) and velocity (measured in radians per second).

To see how to use a rotation gesture, follow these steps:

  1. Click the Main.storyboard file in the Navigator pane. Xcode displays the single view.
  2. Click the Library icon to open the Object Library window and look for the Rotate Gesture Recognizer.
  3. Drag and drop the Rotate Gesture Recognizer onto the view. Xcode displays the Rotate Gesture Recognizer in the Document Outline and above the View Controller.
  4. Click the Library icon to open the Object Library window and drag and drop an image view on the user interface.
  5. Click the Attributes Inspector icon in the upper right corner of the Xcode window.
  6. Click in the Background popup menu and choose green color.
  7. Select the User Interaction Enabled check box. This allows the image view to respond to the user.
  8. Click the Align icon in the bottom of the middle Xcode pane. A window appears.
  9. Select the Horizontally in Container and Vertically in Container check boxes and then click the Add 2 Constraints button.
  10. Move the mouse pointer over the image view, hold down the Control key, and Ctrl-drag from the image view to the Rotation Gesture Recognizer icon in the Document Outline or at the top of the View Controller.
  11. Release the Control key and the left mouse button. A window appears.
  12. Choose gestureRecognizers. This link lets the image view detect rotation gestures.
  13. Click the Assistant Editor icon. Xcode displays the Main.storyboard and ViewController.swift file side by side.
  14. Move the mouse pointer over the image view, hold down the Control key, and Ctrl-drag from the image view to the ViewController.swift file underneath the class ViewController line.
  15. Release the Control key and the left mouse button. A popup window appears.
  16. Click in the Name text field, type topImageView, and click the Connect button.
  17. Move the mouse pointer over the Rotation Gesture Recognizer icon in the Document Outline or at the top of the View Controller, hold down the Control key, and Ctrl-drag from the Rotation Gesture Recognizer above the last curly bracket in the ViewController.swift file.
  18. Release the Control key and the left mouse button. A popup window appears.
  19. Click in the Name text field, type rotationDetected, click in the Type popup menu and choose UIRotationGestureRecognizer, and click the Connect button. Xcode creates an IBAction method.
  20. Edit the rotationDetected IBAction method as follows:
@IBAction func rotationDetected(_ sender: UIRotationGestureRecognizer) {
    topImageView.transform = CGAffineTransform(rotationAngle:
    sender.rotation)
}

Let’s see how to duplicate this process through Swift code alone.

import UIKit
class ViewController: UIViewController {
    @IBOutlet var topImageView: UIImageView! 
    var rotateMe: UIRotationGestureRecognizer?
    override func viewDidLoad() {
        super.viewDidLoad()
        topImageView.isUserInteractionEnabled = true 
        topImageView.backgroundColor = UIColor.green
        let rotationGesture = UIRotationGestureRecognizer(target: self, 
            action: #selector(handleRotation)) 
        topImageView.addGestureRecognizer(rotationGesture) 
        rotateMe = rotationGesture
    }
    @objc func handleRotation() {
        topImageView.transform = CGAffineTransform(rotationAngle: rotateMe!.rotation)
    } 
}

Detecting Pan Gestures

A pan gesture occurs when the user holds a fingertip on the screen and moves the fingertip, keeping it pressed on the screen. A pan gesture tracks the velocity and translation where the velocity measures the speed of the pan gesture while the translation measures the movement of the pan gesture.

To see how to use a pan gesture, follow these steps:

  1. Click the Main.storyboard file in the Navigator pane. Xcode displays the single view.
  2. Click the Library icon to open the Object Library window and look for the Pan Gesture Recognizer
  3. Drag and drop the Pan Gesture Recognizer onto the view. Xcode displays the Pan Gesture Recognizer in the Document Outline and above the View Controller.
  4. Click the Library icon to open the Object Library window and drag and drop an image view in the center of the user interface.
  5. Click the Attributes Inspector icon in the upper right corner of the Xcode window.
  6. Click in the Background popup menu and choose green color.
  7. Select the User Interaction Enabled check box. This allows the image view to respond to the user.
  8. Click the Align icon in the bottom of the middle Xcode pane. A window appears.
  9. Select the Horizontally in Container and Vertically in Container check boxes and then click the Add 2 Constraints button.
  10. Move the mouse pointer over the image view, hold down the Control key, and Ctrl-drag from the image view to the Pan Gesture Recognizer icon in the Document Outline or at the top of the View Controller.
  11. Release the Control key and the left mouse button. A window appears.
  12. Choose gestureRecognizers. This link lets the image view detect pan gestures.
  13. Click the Assistant Editor icon. Xcode displays the Main.storyboard and ViewController.swift file side by side.
  14. Move the mouse pointer over the image view, hold down the Control key, and Ctrl-drag from the image view to the ViewController.swift file underneath the class ViewController line.
  15. Release the Control key and the left mouse button. A popup window appears.
  16. Click in the Name text field, type topImageView, and click the Connect button.
  17. Add the following two lines underneath the IBOutlet:
var xOrigin:CGFloat = 0
var yOrigin:CGFloat = 0

Edit the viewDidLoad method as follows:

override func viewDidLoad() {
    super.viewDidLoad()
    xOrigin = topImageView.center.x
    yOrigin = topImageView.center.y
}
  1. Move the mouse pointer over the Pan Gesture Recognizer icon in the Document Outline or at the top of the View Controller, hold down the Control key, and Ctrl-drag from the Pan Gesture Recognizer above the last curly bracket in the ViewController. swift file.
  2. Release the Control key and the left mouse button. A popup window appears.
  3. Click in the Name text field, type panDetected, click in the Type popup menu and choose UIPanGestureRecognizer, and click the Connect button. Xcode creates an IBAction method.
  4. Edit the panDetected IBAction method as follows:
@IBAction func panDetected(_ sender: UIPanGestureRecognizer) { 
    let translation = sender.translation(in: view) 
    topImageView.center = CGPoint(x: xOrigin + translation.x, y: yOrigin + translation.y)
}

Let’s see how to duplicate this process through Swift code alone.

import UIKit
class ViewController: UIViewController {
    @IBOutlet var topImageView: UIImageView! 
    var rotateMe: UIRotationGestureRecognizer?
    override func viewDidLoad() { 
        super.viewDidLoad() 
        topImageView.isUserInteractionEnabled = true
        topImageView.backgroundColor = UIColor.green
        let rotationGesture = UIRotationGestureRecognizer(target: self, 
            action: #selector(handleRotation)) 
        topImageView.addGestureRecognizer(rotationGesture) 
        rotateMe = rotationGesture
    }
    @objc func handleRotation() {
        topImageView.transform = CGAffineTransform(rotationAngle: rotateMe!.rotation)
    } 
} 

Detecting Screen Edge Pan Gestures

One unique gesture that an app can detect is called a screen edge pan. This occurs when the user slides a fingertip from the top, bottom, left, or right edge of the screen. By default, iOS uses top edge pans to display notifications and bottom edge pans to display the Control Center. You’ll need to override these default iOS edge pans if you want your own app to detect top or bottom edge pans.

When creating a screen edge pan gesture, you’ll also need to create a separate screen edge pan gesture recognizer for each edge you want to detect. So if you want your app to detect a bottom and a left edge pan, you’ll need to create two separate gesture recognizers, one to detect bottom edge pans and a second to detect left edge pans.

To see how to use a screen edge pan gestures, follow these steps:

  1. Click the Main.storyboard file in the Navigator pane. Xcode displays the single view.
  2. Click the Library icon to open the Object Library window and look for the Screen Edge Pan Gesture Recognizer
  3. Drag and drop the Screen Edge Pan Gesture Recognizer onto the view. Xcode displays the Screen Edge Pan Gesture Recognizer in the Document Outline and above the View Controller.
  4. Click the Attributes Inspector icon in the upper right corner of the Xcode window.
  5. Select the Bottom check box to recognize bottom screen edge pan gestures.
  6. Click the Assistant Editor icon. Xcode displays the Main.storyboard and ViewController.swift file side by side.
  7. Move the mouse pointer over the Screen Edge Pan Gesture Recognizer at the top of the View Controller or in the Document Outline, hold down the Control key, and Ctrl-drag above the last curly bracket at the bottom of the ViewController.swift file.
  8. Release the Control key and the left mouse button. A popup window appears.
  9. Click in the Name text field and type bottomEdgeDetected, click in the Type popup menu and choose UIScreenEdgePanGestureRecognizer, then click the Connect button.
  10. Edit this bottomEdgeDetected IBAction method as follows:
@IBAction func bottomEdgeDetected(_ sender: UIScreenEdgePanGestureRecognizer) {
    print ("Bottom edge pan gesture")
}
  1. Click the Screen Edge Pan Gesture Recognizer in the Document Outline and press ENTER. Xcode highlights the entire name.
  2. Type Bottom Edge Gesture and press ENTER to rename your gesture recognizer.
  3. Add the following method underneath the viewDidLoad method:
override var preferredScreenEdgesDeferringSystemGestures: UIRectEdge {
    return UIRectEdge.bottom 
}
  1. Click the Main.storyboard in the Navigator pane.
  2. Click the Library icon to open the Object Library window.
  3. Drag and drop another Screen Edge Pan Gesture Recognizer onto the view. Xcode displays the second Screen Edge Pan Gesture Recognizer in the Document Outline and above the View Controller.
  4. Click the Screen Edge Pan Gesture Recognizer in the Document Outline and press ENTER to highlight the entire name. Then type Left Edge Gesture and press ENTER.
  5. Click this Left Edge Gesture in the Document Outline and click the Attributes Inspector icon in the upper right corner of the Xcode window.
  6. Select the Left check box to define it to detect left screen edge pan gestures.
  7. Move the mouse pointer over the Left Edge Gesture in the Document Outline, hold down the Control key, and Ctrl-drag above the last curly bracket at the bottom of the ViewController. swift file.
  8. Release the Control key and the left mouse button. A popup window appears.
  9. Click in the Name text field, type leftEdgeDetected, click in the Type popup menu and choose UIScreenEdgePanGestureRecognizer, then click the Connect button.
  10. Edit this leftEdgeDetected IBAction method as follows:
@IBAction func leftEdgeDetected(_ sender: UIScreenEdgePanGestureRecognizer) {
    print ("Left edge pan gesture")
}

Let’s see how to duplicate this process through Swift code alone.

override func viewDidLoad() {
    super.viewDidLoad()
    let bottomEdgeGesture = UIScreenEdgePanGestureRecognizer(target: self, 
        action: #selector(handleBottomEdge)) 
    myView.addGestureRecognizer(bottomEdgeGesture) 
    bottomEdgeGesture.edges = .bottom
    let leftEdgeGesture = UIScreenEdgePanGestureRecognizer(target: self, 
        action: #selector(handleLeftEdge)) 
    myView.addGestureRecognizer(leftEdgeGesture) 
    leftEdgeGesture.edges = .left
}

override var preferredScreenEdgesDeferringSystemGestures: UIRectEdge {
    return UIRectEdge.bottom 
}

@objc func handleBottomEdge() {
    print ("Bottom edge pan gesture")
}

@objc func handleLeftEdge() {
    print ("Left edge pan gesture")
}

Detecting Swipe Gestures

Swipe gestures occur when the user swipes across the screen in one of the four directions: up, down, left, or right. You can define how many fingertips are needed for a swipe and also the direction you want the gesture recognizer to detect.

Each swipe gesture recognizer can only detect swipes in a single direction. That means if you want to detect an up and down swipe, you’ll need to define two separate swipe gesture recognizers where one recognizes only up swipes and the second only recognizes down swipes.

To see how to use a swipe gesture, follow these steps:

  1. Click the Main.storyboard file in the Navigator pane. Xcode displays the single view.
  2. Click the Library icon to open the Object Library window and look for the Pan Gesture Recognizer
  3. Drag and drop the Swipe Gesture Recognizer onto the view. Xcode displays the Swipe Gesture Recognizer in the Document Outline and above the View Controller.
  4. Click the Swipe Gesture Recognizer in the Document Outline and press ENTER. Then type Right Swipe Gesture and press ENTER.
  5. Drag and drop a second Swipe Gesture Recognizer onto the view. Xcode displays the Swipe Gesture Recognizer in the Document Outline and above the View Controller.
  6. Click the Swipe Gesture Recognizer in the Document Outline and press ENTER. Then type Up Swipe Gesture and press ENTER.
  7. Click the Library icon to open the Object Library window and drag and drop an image view in the center of the user interface.
  8. Click the Attributes Inspector icon in the upper right corner of the Xcode window.
  9. Click in the Background popup menu and choose green color.
  10. Select the User Interaction Enabled check box. This allows the image view to respond to the user.
  11. Click the Align icon in the bottom of the middle Xcode pane. A window appears.
  12. Select the Horizontally in Container and Vertically in Container check boxes and then click the Add 2 Constraints button.
  13. Move the mouse pointer over the image view, hold down the Control key, and Ctrl-drag from the image view to the Right Swipe Gesture icon in the Document Outline or at the top of the View Controller.
  14. Release the Control key and the left mouse button. A window appears.
  15. Choose gestureRecognizers. This link lets the image view detect right swipe gestures.
  16. Move the mouse pointer over the image view, hold down the Control key, and Ctrl-drag from the image view to the Up Swipe Gesture icon in the Document Outline or at the top of the View Controller.
  17. Release the Control key and the left mouse button. A window appears.
  18. Choose gestureRecognizers. This link lets the image view detect up swipe gestures.
  19. Click Up Swipe Gesture in the Document Outline and click the Attributes Inspector icon in the upper right corner of the Xcode window.
  20. Click in the Swipe popup menu and choose Up
  21. Click the Assistant Editor icon. Xcode displays the Main.storyboard and ViewController.swift file side by side.
  22. Move the mouse pointer over the image view, hold down the Control key, and Ctrl-drag from the image view to the ViewController.swift file underneath the class ViewController line.
  23. Release the Control key and the left mouse button. A popup window appears.
  24. Click in the Name text field, type topImageView, and click the Connect button.
  25. Move the mouse pointer over the Right Swipe Gesture icon in the Document Outline or at the top of the View Controller, hold down the Control key, and Ctrl-drag from the Right Swipe Gesture to above the last curly bracket in the ViewController.swift file.
  26. Release the Control key and the left mouse button. A popup window appears.
  27. Click in the Name text field, type rightSwipeDetected, click in the Type popup menu and choose UISwipeGestureRecognizer, and click the Connect button. Xcode creates an IBAction method.
  28. Edit the rightSwipeDetected IBAction method as follows:
@IBAction func rightSwipeDetected(_ sender: UISwipeGestureRecognizer) {
    topImageView.center = CGPoint(x: topImageView.center.x +
    topImageView.frame.width, y: topImageView.center.y)
}
  1. Move the mouse pointer over the Up Swipe Gesture icon in the Document Outline or at the top of the View Controller, hold down the Control key, and Ctrl-drag from the Right Swipe Gesture to above the last curly bracket in the ViewController.swift file.
  2. Release the Control key and the left mouse button. A popup window appears.
  3. Click in the Name text field, type upSwipeDetected, click in the Type popup menu and choose UISwipeGestureRecognizer, and click the Connect button. Xcode creates an IBAction method.
  4. Edit the upSwipeDetected IBAction method as follows:
@IBAction func upSwipeDetected(_ sender: UISwipeGestureRecognizer) {
    topImageView.center = CGPoint(x: topImageView.center.x, y:
    topImageView.center.y - topImageView.frame.height)
}

Let’s see how to duplicate this process through Swift code alone.

import UIKit
class ViewController: UIViewController {
    @IBOutlet var topImageView: UIImageView! 
    override func viewDidLoad() {
        super.viewDidLoad() 
        topImageView.isUserInteractionEnabled = true
        topImageView.backgroundColor = UIColor.green
        let downSwipeGesture = UISwipeGestureRecognizer(target: self, 
            action: #selector(handleDownSwipe)) 
        topImageView.addGestureRecognizer(downSwipeGesture) 
        downSwipeGesture.direction = .down
        let leftSwipeGesture = UISwipeGestureRecognizer(target: self, 
            action: #selector(handleLeftSwipe)) 
        topImageView.addGestureRecognizer(leftSwipeGesture) 
        leftSwipeGesture.direction = .left
    }
    @objc func handleDownSwipe() {
        topImageView.center = CGPoint(x: topImageView.center.x, 
            y: topImageView.center.y + topImageView.frame.height)
    }
    @objc func handleLeftSwipe() {
        topImageView.center = CGPoint(x: topImageView.center.x - topImageView.frame.width, 
            y: topImageView.center.y)
    } 
}

Detecting Long Press Gestures

A long press gesture occurs when the user presses one or more fingertips on the screen for a fixed amount of time where the fingertips don’t move very far. To define a long press, you can modify the following properties:

  • .minimumPressDuration – Defines how long one or more fingertips must press down on the screen until the long press is recognized
  • .numberOfTouchesRequired – Defines how many fingertips must press on the screen until the longer press gesture is recognized
  • .allowableMovement – Defines how far fingertips can move before the long press gesture fails

To see how to use a long press gesture, follow these steps:

  1. Click the Main.storyboard file in the Navigator pane. Xcode displays the single view.
  2. Click the Library icon to open the Object Library window and look for the Long Press Gesture Recognizer.
  3. Drag and drop the Long Press Gesture Recognizer onto the view. Xcode displays the Long Press Gesture Recognizer in the Document Outline and above the View Controller.
  4. Click the Library icon to open the Object Library window and drag and drop an image view on the user interface.
  5. Click the Attributes Inspector icon in the upper right corner of the Xcode window.
  6. Click in the Background popup menu and choose green color.
  7. Select the User Interaction Enabled check box. This allows the image view to respond to the user.
  8. Click the Align icon in the bottom of the middle Xcode pane. A window appears.
  9. Select the Horizontally in Container and Vertically in Container check boxes and then click the Add 2 Constraints button.
  10. Move the mouse pointer over the image view, hold down the Control key, and Ctrl-drag from the image view to the Long Press Gesture Recognizer icon in the Document Outline or at the top of the View Controller.
  11. Release the Control key and the left mouse button. A window appears.
  12. Choose gestureRecognizers. This link lets the image view detect long press gestures.
  13. Click the Assistant Editor icon. Xcode displays the Main.storyboard and ViewController.swift file side by side.
  14. Move the mouse pointer over the image view, hold down the Control key, and Ctrl-drag from the image view to the ViewController.swift file underneath the class ViewController line.
  15. Release the Control key and the left mouse button. A popup window appears.
  16. Click in the Name text field, type topImageView, and click the Connect button.
  17. Move the mouse pointer over the Long Press Gesture Recognizer icon in the Document Outline or at the top of the View Controller, hold down the Control key, and Ctrl-drag from the Long Press Gesture Recognizer above the last curly bracket in the ViewController.swift file.
  18. Release the Control key and the left mouse button. A popup window appears.
  19. Click in the Name text field, type longPressDetected, click in the Type popup menu and choose UILongPressGestureRecognizer, and click the Connect button. Xcode creates an IBAction method.
  20. Edit the longPressDetected IBAction method as follows:
@IBAction func longPressDetected(_ sender: UILongPressGestureRecognizer) {
    topImageView.backgroundColor = UIColor.red
}

Let’s see how to duplicate this process through Swift code alone.

import UIKit
class ViewController: UIViewController {
    @IBOutlet var topImageView: UIImageView! 
    override func viewDidLoad() {
        super.viewDidLoad() 
        topImageView.isUserInteractionEnabled = true
        topImageView.backgroundColor = UIColor.green
        let longPressGesture = UILongPressGestureRecognizer(target: self, 
            action: #selector(handleLongPress)) 
        topImageView.addGestureRecognizer(longPressGesture) 
    }
    @objc func handleLongPress() { 
        topImageView.backgroundColor = UIColor.red
    } 
}