Detect Long Press Gesture iOS Tutorial

Long-press gestures are a type of a continuous gesture. UIKit will detect if a press is pushed long instead of a single tap. In this tutorial a long-press gesture is detected, which will display an an alert view. This tutorial is made with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOSLongPressGestureTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

Go to the Storyboard and drag a Button to the main view. Set the title of the button to "Press me".  Select the Resolve Auto Layout Issues button and select Reset to Suggested Constraints.

Drag a Long Press Gesture Recognizer from the Object Library on top of the Button. The Storyboard should look like this.

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the Long Press Gesture Recognizer to the ViewController class and create the following Action

Ctrl  and drag from the Long Press Gesture Recogniser to the Button and select delegate. The button will now detect the long press gesture.


Go to the ViewController.swift file and implement the handleGesture method

@IBAction func handleGesture(_ sender: UILongPressGestureRecognizer) {
    if sender.state == .began
        let alertController = UIAlertController(title: nil, message:
            "Long-Press Gesture Detected", preferredStyle: .alert)
        alertController.addAction(UIAlertAction(title: "OK", style: .default,handler: nil))

        present(alertController, animated: true, completion: nil)

The began UIRecognizerState is a continuous state. If this is recognised an Alert View is Presented. Build and Run the project and long press on the Press me Button.

You can download the source code of the IOSLongPressGestureTutorial at the ioscreator repository on Github.