Contents

Handling swipe gestures

Detect a horizontal or vertical swipe motion on the screen, and use it to trigger navigation through your content.

Overview

A swipe gesture occurs when a person moves one or more fingers across the screen in a specific horizontal or vertical direction. Use the UISwipeGestureRecognizer class to detect swipe gestures.

You can attach a gesture recognizer in one of these ways:

  • Programmatically. Call the addGestureRecognizer(_:) method of your view.

  • In Interface Builder. Drag the appropriate object from the library and drop it onto your view.

[Image]

A UISwipeGestureRecognizer object tracks the motion of a person’s finger across the screen either horizontally or vertically. A swipe requires a person’s finger to move in a specific direction and not deviate significantly from the main direction of travel. (The direction and number of fingers required for the gesture are configurable.) Swipe gestures are discrete, so your action method is called only after the gesture ends successfully. As a result, swipes are most appropriate when you care only about the results of the gesture and not about tracking the movement of a person’s finger.

The following code shows a skeletal action method for a swipe gesture recognizer. You use a method like this to perform a task when the gesture is recognized. Because the gesture is discrete, the gesture recognizer doesn’t enter the began or changed states.

@IBAction func swipeHandler(_ gestureRecognizer : UISwipeGestureRecognizer) {
    if gestureRecognizer.state == .ended {
        // Perform action.
    }
}

If the code for your swipe gesture recognizer isn’t called, check to see if the following conditions are true, and make corrections as needed:

See Also

Gestures