46

Detect Long Press Gesture iOS Tutorial

 5 years ago
source link: https://www.tuicool.com/articles/hit/VNNJbmu
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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.

6JZ7ner.png!web

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.

I77zmir.png!web

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.

NBzmaeq.png!web

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

n2umQ3V.png!web

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

ZFJRBnY.png!web

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

yiiqQru.png!web

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.

67buQjz.png!web

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


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK