在 minimumPressDuration 之前调用 NSPressGestureRecognizer

Posted

技术标签:

【中文标题】在 minimumPressDuration 之前调用 NSPressGestureRecognizer【英文标题】:NSPressGestureRecognizer called before minimumPressDuration 【发布时间】:2016-09-07 12:40:30 【问题描述】:

我需要我的NSButton 来响应常规点击以及长按。我像这样添加NSPressGestureRecognizer

override func viewDidLoad() 
    super.viewDidLoad()

    let gr = NSPressGestureRecognizer()
    gr.minimumPressDuration = 1
    gr.action = #selector(handleLongPress)
    button.addGestureRecognizer(gr)  


func handleLongPress(gr: NSPressGestureRecognizer) 

    if gr.state == .Began 
        Swift.print("long press")
    


不幸的是,handleLongPress 即使在短时间单击或双击时也会随机触发。即使我将minimumPressDuration 设置为更高的值,它也会发生。

我尝试过使用shouldBeRequiredToFailByGestureRecognizer,但并没有解决问题。

我的代码有什么遗漏吗?

【问题讨论】:

state == .Began,按下手势开始。当state == .Ended 时,按下手势已被识别。将if gr.state == .Began 更改为if gr.state == .Ended。阅读documentation。 【参考方案1】:

我已经通过处理多个手势识别器解决了这个问题:

类必须实现NSGestureRecognizerDelegate

var singleClick:NSClickGestureRecognizer?
var longClick:NSPressGestureRecognizer?

override func viewDidLoad() 
    super.viewDidLoad()

    longClick = NSPressGestureRecognizer()
    longClick!.minimumPressDuration = 1
    longClick!.action = #selector(handleGestureLong)
    longClick!.delegate = self

    singleClick = NSClickGestureRecognizer()
    singleClick?.numberOfClicksRequired = 1
    singleClick!.action = #selector(handleGestureSingle)
    singleClick!.delegate = self

    btn.addGestureRecognizer(longClick!)
    btn.addGestureRecognizer(singleClick!)



func gestureRecognizer(gestureRecognizer: NSGestureRecognizer, shouldRequireFailureOfGestureRecognizer otherGestureRecognizer: NSGestureRecognizer) -> Bool 
    if gestureRecognizer == singleClick && otherGestureRecognizer == longClick 
        return false
    
    return true


func handleGestureSingle(gr: NSClickGestureRecognizer) 

    switch gr.state 

    case .Ended:
        print("single click")
        break
    default:
        break

    


func handleGestureLong(gr: NSPressGestureRecognizer) 

    switch gr.state 

    case .Began:
        print("long click")
        break
    default:
        break

    

【讨论】:

以上是关于在 minimumPressDuration 之前调用 NSPressGestureRecognizer的主要内容,如果未能解决你的问题,请参考以下文章

如何比较 iOS 上的手势类型?

tableview长按响应的实现

ios手势识别之长按

在objective-c中,睡眠发生在它之前的代码之前

为啥必须在可选链接之前使用点运算符 - 在函数之前? [复制]

何时过滤/清理数据:在数据库插入之前还是在显示之前?