禁用长按

Disable a longpress

如何禁用长按?

我在 viewcontroller 中设置了一个长按,它工作正常,但我希望它在我按下另一个按钮后停止工作。

我可以在按下按钮 B 后添加一个标志并将其设置为 false,然后长按停止工作,如下所示:

func longpress(gestureRecognizer: UIGestureRecognizer)  { 
   if flag = true { 
       // action 
   } 
}

但我认为这不是正确的方法。那么,正确的方法是什么?

您需要查看 UILongPressGestureRecognizer 的超类,UIGestureRecognizer. It has a property isEnabled 可用于关闭识别并再次打开它。

编辑:根据海报请求在下面添加示例代码

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