Swift - 如何识别单击和双击之间的区别

Swift - How to identify difference between single and double taps

我知道有一些帖子解决了单击和双击问题之间的识别差异,但它们要么已经过时,要么是在 C++ 中。所以,我想知道如何识别单击和双击之间的区别,因为每次我双击系统都认为它是一个水龙头。我确实将 numberOfTaps 的值设置为 1 表示单击,2 表示双击。

    let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(respondToTapGesture(gesture:)))
    view.addGestureRecognizer(tap)

    tap.numberOfTapsRequired = 1

let doubleTap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(respontToDoubleTapGesture(gesture:)))
    view.addGestureRecognizer(doubleTap)

    doubleTap.numberOfTapsRequired = 2

为了识别所采取的动作或区分单击和双击,您需要使手势失败,只需在下面添加该代码

tap.require(toFail: doubleTap) 

问题是您有两个不同的识别器试图识别手势。

此代码将允许它们中的每一个工作:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

您需要确保已将控制器声明为手势识别委托:

class FromDB: UICollectionViewController, UICollectionViewDelegateFlowLayout, UIGestureRecognizerDelegate {
}

您还需要要求单击失败才能启动双击:

tap.require(toFail: doubleTap)