第一种方式
1. 给UIButton 添加扩展
UIButton+tapTime
import UIKit
import Foundation
extension UIButton {
private static var ForbidIntervalKey = "ForbidIntervalKey"
private static var LastClickTimeKey = "LastClickTimeKey"
/// 按钮不能被重复点击的时间间隔(默认两秒)
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)
}
}
/// 存储上次点击的时间(默认是1970年的时间)
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("被点击了....")
}
💚这种方式代码量大, 每次需要调用方法转换和配置时间
第二种方式
@IBAction func pushClick(_ sender: Any) {
let button = sender as! UIButton
button.isEnabled = false
DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
button.isEnabled = true
}
/*要做的事*/
print("被点击了...")
}
💚 按钮会出现button的非可用状态样式
第三种方式 (RxSwift)
pushButton.rx.tap.asObservable()
.throttle(2, scheduler: MainScheduler.instance)
.bind {
print("被点击了...")
}
.disposed(by: bag)
💚 这种方式最简单, 但是需要RxSwift框架
网友评论