【问题标题】:Disable a longpress禁用长按
【发布时间】:2016-11-08 05:18:38
【问题描述】:

如何禁用长按?

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

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

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

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

【问题讨论】:

    标签: ios swift3 uigesturerecognizer


    【解决方案1】:

    你需要查看 UILongPressGestureRecognizer 的超类,UIGestureRecognizer。它有一个属性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")")
            }
        }
    

    【讨论】:

    • 你打败了我。 (已投票。)很容易忘记检查一个类的超类。通常你需要的东西隐藏在类层次结构的更深处。
    • 是的,但我如何将其设置为,比如说:UILongPress.isenable = false 从按钮内部?因为这个 UILongPress 是未解析的标识符....
    • 你需要引用一个实例。创建 UILongPressGestureRecognizer 时,将其副本保存在视图控制器的属性中,或者如果您在界面生成器中创建它,则拖出 IBOutlet。在该属性上将 isEnabled 设置为 false。
    • 我保存了一个这样的副本:UIlongPressGlobal = UILongPress.我在 viewcontroller 类中这样定义它: let longPressGlobal = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.longpress(gestureRecognizer:)))。当我将其设置为 false 时,它​​什么也不做: UILongPressGlobal.isenabled = false 。 (我没有把它拖到 IBOutlet 上)
    • 我更新了答案。示例代码在我运行时有效。故事板上有两个按钮,一个是我添加的长按按钮,两个具有称为按钮的插座,另一个具有 IBAction tapDisableButton。
    猜你喜欢
    • 2021-05-14
    • 2013-04-30
    • 2023-01-12
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多