0
votes

I want to customize my long press gesture recognizer in the following ways:

1) When I hold down on an object for 0.5 seconds, the object darkens, and 2) When I continue to hold down on the object for another second (total of 1.5 seconds), some action happens (e.g. the object disappears).

Essentially, by holding down on an object for a minimum of 1.5 seconds, two actions happened at two separate times. I also have a tap gesture recognizer, which might affect things.

2
if user holds more than 1.5 secs you need both actions or only the more time action?Reinier Melian
@ReinierMelian I want both actions to occur.AJ Z.

2 Answers

3
votes

The answer from @nathan is essentially fine but a detail is missing you need to implement the UIGestureRecognizerDelegate to allow both gestures works simultaneously, so this is my code

class ViewController: UIViewController, UIGestureRecognizerDelegate{   

    override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.

    //this for .5 time
    let firstGesture = UILongPressGestureRecognizer(target: self, action: #selector(firstMethod))
    //this for 1.5
    let secondGesture = UILongPressGestureRecognizer(target: self, action: #selector(secondMethod))
    secondGesture.minimumPressDuration = 1.5
    firstGesture.delegate = self
    secondGesture.delegate = self
    self.view.addGestureRecognizer(firstGesture)
    self.view.addGestureRecognizer(secondGesture)

}

func firstMethod() {
    debugPrint("short")
}

func secondMethod() {
    debugPrint("long")
}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool{
    return true
}
}

Hope this help

3
votes

See Reinier's solution as it's the correct one. This one adds a delay to satisfy require(toFail:)


You can set the timing using the property minimumPressDuration (in seconds, default is 0.5)

let quickActionPress = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.zeroFiveSecondPress(gesture:))) // 0.5 seconds by default
let laterActionPress = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.oneFiveSecondPress(gesture:)))
laterActionPress.minimumPressDuration = 1.5

someView.addGestureRecognizer(quickActionPress)
someView.addGestureRecognizer(laterActionPress)

// If 1.5 detected, only execute that one
quickActionPress.require(toFail: laterActionPress)

@objc func zeroFiveSecondPress(gesture: UIGestureRecognizer) {
    // Do something
    print("0.5 press")
}

@objc func oneFiveSecondPress(gesture: UIGestureRecognizer) {
    zeroFiveSecondPress(gesture: gesture)
    // Do something else
    print("1.5 press")
}