如何取消 LongPressGestureRecognizer?

Boo*_*unz 2 uigesturerecognizer ios swift

我有一个LongPressGestureRecognizer分配给它的视图,它调用以下方法:

@IBAction func longPressOnView1Recognized(_ sender: UIGestureRecognizer) {

    if sender.state == .began {
        // this runs when user's finger is down a "long time"
    }
    if sender.state == .ended {
        // this runs when user's finger goes up again after the .began state 
    }

}
Run Code Online (Sandbox Code Playgroud)

这一切都按预期工作,但我试图找到一种(好的/正确的)方法,能够cancel在用户的手指仍然向下时以编程方式长按识别器(在某些情况下)。

也就是说,当用户的手指仍然在视图上时,识别器已经进入 .began 状态,(但在用户抬起手指之前 - 在识别器进入 .end 状态之前)......是否有一些代码我们可以运行这将阻止上面的方法在用户抬起手指时触发……就像过早地告诉 IOS 在此手势的其余部分不再监听 UP 事件?

我已经阅读了这些文档,但我对 IOS 触摸没有太多经验,而且我似乎找不到任何为此目的而设计的方法。

我的GestureRecognizer.reset()似乎没有做我所描述的。

我能想到两种可能:

1) 一个布尔标志,将进入if sender.state == .ended {}闭包

2)这个:

myLongPressRecognizer.isEnabled = false
myLongPressRecognizer.isEnabled = true
Run Code Online (Sandbox Code Playgroud)

这两个工作,但似乎不是那么好。

Mat*_*lak 5

你们都擅长禁用和重新启用手势识别器,这样做

myLongPressRecognizer.isEnabled = false
myLongPressRecognizer.isEnabled = true
Run Code Online (Sandbox Code Playgroud)

是完全正确的。

我担心的是您并不完全了解手势识别器。在处理手势识别器时,您应该始终使用 switch 语句。检查评论:

func handleLongPressGestureRecognizer(_ sender: UIGestureRecognizer) {

    switch sender.state {
    case .began:
        // This will be called only once when the gesture starts
        print("Long press did begin at \(sender.location(in: sender.view))")
    case .changed:
        // This will be called whenever your finger moves (at some frequency obviously).
        // At this point your long press gesture is acting exactly the same as pan gesture
        print("Long press changed position to \(sender.location(in: sender.view))")
    case .ended:
        // This is when user lifts his finger assuming the gesture was not canceled
        print("Long press ended at \(sender.location(in: sender.view))")
    case .cancelled:
        // This is equally important as .ended case. You gesture may be canceled for many reasons like a system gesture overriding it. Make sure to implement logic here as well.
        print("Long press canceled at \(sender.location(in: sender.view))")
    case .failed, .possible:
        // These 2 have been added additionally at some point. Useless as far I am concerned.
        break
    }

}
Run Code Online (Sandbox Code Playgroud)

所以至少你应该处理取消状态。但还要注意,只要移动手势,就会触发更改的状态。