按鈕被連點(diǎn),單點(diǎn)手勢(shì)被連續(xù)觸發(fā)有時(shí)候我們的APP會(huì)出現(xiàn)各種糟糕的現(xiàn)象(例如: 綁定事件是彈出個(gè)頁(yè)面,連點(diǎn)之后連續(xù)彈出多個(gè)相同的頁(yè)面,或者綁定某個(gè)指令,連點(diǎn)之后連續(xù)下發(fā)多個(gè)指令等等)等等... 防止按鈕的連點(diǎn)我已經(jīng)在之前的文章中總結(jié)過(guò)了,本文總結(jié)的是防止自定義綁定的單點(diǎn)手勢(shì)的連點(diǎn):
廢話不說(shuō),老規(guī)矩上代碼:
import UIKit
class TapGestureManager:UITapGestureRecognizer,UIGestureRecognizerDelegate {
//想間隔的時(shí)長(zhǎng)
var intervalTime: NSTimeInterval?
//用于完成間隔的計(jì)時(shí)器
private var eventTimer: NSTimer?
override init(target: AnyObject?, action: Selector) {
super.init(target: target, action: action)
delegate = self
}
// 是否響應(yīng)觸摸手勢(shì)的代理方法
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
if (eventTimer != nil) {
return false
}
eventTimer = NSTimer(timeInterval: intervalTime ?? 0, target: self, selector: #selector(deinitTimer), userInfo: nil, repeats: false)
NSRunLoop.currentRunLoop().addTimer(eventTimer!, forMode: NSRunLoopCommonModes)
return true
}
func deinitTimer() {
eventTimer?.invalidate()
eventTimer = nil
}
}
以上的代碼就可以防止單點(diǎn)手勢(shì)連續(xù)快速觸發(fā),食用方法如下:
override func viewDidLoad() {
super.viewDidLoad()
// 新建一個(gè)綁定點(diǎn)擊事件的單點(diǎn)手勢(shì)(注: 不一定是綁定一個(gè)事件的手勢(shì),閉包也可以,自己修改這里不贅述)
let tap = TapGestureManager(target: self, action: #selector(test_Tap))
// 設(shè)置手勢(shì)的間隔時(shí)間:10秒
tap.intervalTime = 10
//添加手勢(shì),(搞定!)
userCenterImage.addGestureRecognizer(tap)
}
func test_Tap() {
//...
}