How to detect a long press in iOS?


Long-press (also known as press-and-hold) gestures detect one or more fingers touching the screen for an extended period of time. You configure the minimum duration required to recognize the press and the number of times the fingers must be touching the screen. (The gesture recognizer is triggered only by the duration of the touches and not by the force associated with them.) You might use a long-press gesture to initiate an action on the object being pressed. For example, you might use it to display a context-sensitive menu.

You can read more about it  https://developer.apple.com/documentation/uikit/touches_presses_and_gestures/handling_uikit_gestures/handling_long-press_gestures

Here we will be designing a simple application where we will press a button for certain period of time (Long press) and it will display an alert.

So let’s get started.

Step 1 − Open Xcode → New Projecr → Single View Application → Let’s name it “LongPressGesture”

Step 2 − In Main.storyboard add one button and create @IBOutlet of it and name it “btnLongOutlet”

Step 3 − Now open ViewController.swift and create an object of UILongPressGestureRecognizer()

var longgesture = UILongPressGestureRecognizer

Step 4 − In viewDidLoad() add the following code,

longgesture = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longPress(_:)))
longgesture.minimumPressDuration = 2
btnLongOutlet.addGestureRecognizer(longgesture)

Step 5 − Create a function longPress and add below code,

@objc func longPress(_ sender: UILongPressGestureRecognizer) {
   let alertController = UIAlertController(title: "Long Press", message:
      "Long Press Gesture Detected", preferredStyle: .alert)
      alertController.addAction(UIAlertAction(title: "OK", style: .default,handler: nil))
   present(alertController, animated: true, completion: nil)
}

Step 6 − And you’re done, Run the application, make sure you tap the button for 2 seconds.

Updated on: 30-Jul-2019

695 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements