快速处理单击和双击

时间:2014-12-21 18:52:35

标签: ios swift

我在另一个堆栈溢出问题上找到了一些好的代码,但是当我单击或双击时,我的单击代码正在运行。继承人代码(顺便说一句,双击意味着我点击一次,在0.3秒内我再次点击,而不是两个手指同时点击)

    override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
        let touch: AnyObject? = touches.anyObject()
        if (touch?.tapCount == 2) {
            NSObject.cancelPreviousPerformRequestsWithTarget(self)
        }
    }

    override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
        let touch: AnyObject? = touches.anyObject()
        if (touch?.tapCount == 1) {
            let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.3 * Double(NSEC_PER_SEC)))
            dispatch_after(dispatchTime, dispatch_get_main_queue(), {
                println("this runs only if single tap")
            })
        } else if (touch?.tapCount == 2) {
            println("double tap touches ended")

        }
    }

我认为NSObject.cancelPreviousPerformRequestsWithTarget(self)应该停止单击块运行,但是当我双击时我的println("this runs only if single tap")仍在运行。首先我的双击运行,然后在0.3秒之后,单击代码也会运行..对我做错的任何想法?

1 个答案:

答案 0 :(得分:0)

问题在于

NSObject.cancelPreviousPerformRequestsWithTarget(self)

不会取消

dispatch_after(dispatchTime, dispatch_get_main_queue()
因此,这将永远不会奏效。有关此

的更多详细信息,请参阅我的其他question
相关问题