Reputation: 1255
How can I disable a longpress?
I have set a longpress in a viewcontroller and it's working ok but i'd like it to stop working after I press another button.
I can add a flag and set it to false after I press button B and than the long press stops workingm like this:
func longpress(gestureRecognizer: UIGestureRecognizer) {
if flag = true {
// action
}
}
But I think it's not the right way. SO, What's the right way to do this?
Upvotes: 1
Views: 3489
Reputation: 16327
You need to look at the superclass of UILongPressGestureRecognizer, UIGestureRecognizer. It has a property isEnabled that can be used to turn off recognition and turn it back on again.
EDIT: add example code below per poster request
import UIKit
class ViewController: UIViewController{
@IBOutlet weak var button: UIButton!
private var longPressGestureRecognizer:UILongPressGestureRecognizer!
override func viewDidLoad() {
super.viewDidLoad()
longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPress))
longPressGestureRecognizer.minimumPressDuration = 1
button.addGestureRecognizer(longPressGestureRecognizer)
}
@objc private func longPress (longPressGestureRecognizer: UILongPressGestureRecognizer) {
if longPressGestureRecognizer.state == .began {
print("long press began")
}
}
@IBAction func tapDisableButton(_ sender: Any) {
longPressGestureRecognizer.isEnabled = !longPressGestureRecognizer.isEnabled
print("long press \(longPressGestureRecognizer.isEnabled ? "enabled" : "disabled")")
}
}
Upvotes: 4