第一種方式
1. 給UIButton 添加擴(kuò)展
UIButton+tapTime
import UIKit
import Foundation
extension UIButton {
private static var ForbidIntervalKey = "ForbidIntervalKey"
private static var LastClickTimeKey = "LastClickTimeKey"
/// 按鈕不能被重復(fù)點(diǎn)擊的時(shí)間間隔(默認(rèn)兩秒)
var forbidInterval: TimeInterval {
get {
if let interval = objc_getAssociatedObject(self, &UIButton.ForbidIntervalKey) as? TimeInterval {
return interval
}
return 2
}
set {
objc_setAssociatedObject(self, &UIButton.ForbidIntervalKey, newValue as TimeInterval, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// 存儲(chǔ)上次點(diǎn)擊的時(shí)間(默認(rèn)是1970年的時(shí)間)
private var lastClickDate: Date {
get {
if let lastDate = objc_getAssociatedObject(self, &UIButton.LastClickTimeKey) as? Date {
return lastDate
}
return Date.init(timeIntervalSince1970: 0)
}
set {
objc_setAssociatedObject(self, &UIButton.LastClickTimeKey, newValue as Date, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func startForbidContinuousClick() {
if let originalMethod: Method = class_getInstanceMethod(self.classForCoder, #selector(UIButton.sendAction)),
let newMethod: Method = class_getInstanceMethod(self.classForCoder, #selector(UIButton.jf_sendAction(action:to:forEvent:))) {
method_exchangeImplementations(originalMethod, newMethod)
}
}
@objc dynamic func jf_sendAction(action: Selector, to target: AnyObject?, forEvent event: UIEvent?) {
if Date().timeIntervalSince(lastClickDate) > forbidInterval {
self.jf_sendAction(action: action, to: target, forEvent: event)
lastClickDate = Date()
}
}
}
2.使用
pushButton.startForbidContinuousClick()
pushButton.forbidInterval = 1.5
@IBAction func pushVC(_ sender: Any) {
print("被點(diǎn)擊了....")
}
??這種方式代碼量大, 每次需要調(diào)用方法轉(zhuǎn)換和配置時(shí)間
第二種方式
@IBAction func pushClick(_ sender: Any) {
let button = sender as! UIButton
button.isEnabled = false
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
button.isEnabled = true
}
/*要做的事*/
print("被點(diǎn)擊了...")
}
?? 按鈕會(huì)出現(xiàn)button的非可用狀態(tài)樣式
第三種方式 (RxSwift)
pushButton.rx.tap.asObservable()
.throttle(2, scheduler: MainScheduler.instance)
.bind {
print("被點(diǎn)擊了...")
}
.disposed(by: bag)
?? 這種方式最簡(jiǎn)單, 但是需要RxSwift框架