如何取消UILongPressGestureRecognizer?

问题描述 投票:1回答:3

我有一个视图,分配给它的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状态,(但在用户抬起手指之前 - 在识别器进入.ended状态之前)...是否有一些代码我们可以运行,这将阻止上述方法在用户抬起手指时触发...就像过早地告诉IOS不再为此手势的其余部分监听UP事件一样?

我已经阅读了这些docs,但我对IOS touch没有那么多经验,而且我似乎无法找到任何专为此目的而设计的方法。

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

我可以想到两种可能性:

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

2)这个:

myLongPressRecognizer.isEnabled = false
myLongPressRecognizer.isEnabled = true

这两项工作似乎都不那么好。

ios swift uigesturerecognizer
3个回答
2
投票

您可以通过禁用和重新启用手势识别器来做到这一点

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
    }

}

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


1
投票

你已经掌握了解决方案。切换qazxsw poi qazxsw poi是最好的方式。无法设置UILongPressGestureRecognizer属性,因为它是get-only属性。

isEnabled

state财产记录为:

默认为YES。禁用手势识别器将不会接收到触摸。当更改为否时,如果手势识别器当前正在识别手势,则手势识别器将被取消。


1
投票

您可以导入手势识别器标头:

open var state: UIGestureRecognizer.State { get } // the current state of the gesture recognizer

这将使isEnabled属性成为readwrite属性。因此,要取消手势,只需将其import UIKit.UIGestureRecognizer 更改为state

因此,例如,您可以在识别出以下内容之后一秒钟取消长按手势识别器:

state
© www.soinside.com 2019 - 2024. All rights reserved.