我有一个分配了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
    }

}

所有这一切都按预期工作,但是我试图找到一种(好的/正确的)方法,可以在用户的​​手指仍然不放的情况下(在某些情况下)以编程方式对长按识别器进行cancel编码。

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

我已经阅读了这些docs,但是我对IOS touch没有太多的经验,而且我似乎找不到用于此目的的任何方法。

我的GestureRecognizer.reset()似乎不符合我的描述。

我可以想到两种可能性:

1)一个布尔标志,它将放在if sender.state == .ended {}闭包内

2):
myLongPressRecognizer.isEnabled = false
myLongPressRecognizer.isEnabled = true

这两种方法都可以,但是看起来并不那么出色。

最佳答案

禁用和重新启用手势识别器都很不错

myLongPressRecognizer.isEnabled = false
myLongPressRecognizer.isEnabled = true

是完全正确的。

我担心的是您不完全了解手势识别器。处理手势识别器时,应始终使用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
    }

}

因此,至少您应该处理已取消的状态。但也请注意,无论何时移动手势,都会触发更改后的状态。

10-07 19:49
查看更多