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 9 and built for iOS 11.

Open Xcode and create a new Single View App.

For product name, use IOS11LongGestureTutorial 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 Button and select the Auto Layout align button. Select the "Horizontally in Container" checkbox and click "Add 1 Constraint".

Select the Button and select the Auto Layout pin button. Pin the Button to the top and and click "Add 1 Constraint".

Drag a Long Press Gesture Recognizer from the Object Library on top of the Button. The Storyboard should look like this.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 == UIGestureRecognizerState.began
    {
        let alertController = UIAlertController(title: nil, message:
                "Long-Press Gesture Detected", preferredStyle: UIAlertControllerStyle.alert)
        alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default,handler: nil))
            
        self.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 press long on the Press me Button.

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