# How to detect a long press in iOS?

iOSApps/ApplicationsMobile Development

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.

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

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) {
}