typealias ActionBlock = ((UIButton)->Void)
extension UIButton {
private struct AssociatedKeys {
static var ActionBlock = "ActionBlock"
static var ActionDelay = "ActionDelay"
}
/// 運(yùn)行時(shí)關(guān)聯(lián)
private var actionBlock: ActionBlock? {
set {
objc_setAssociatedObject(self, &AssociatedKeys.ActionBlock, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &AssociatedKeys.ActionBlock) as? ActionBlock
}
}
private var actionDelay: TimeInterval {
set {
objc_setAssociatedObject(self, &AssociatedKeys.ActionDelay, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, &AssociatedKeys.ActionDelay) as? TimeInterval ?? 0
}
}
/// 點(diǎn)擊回調(diào)
@objc private func btnDelayClick(_ button: UIButton) {
actionBlock?(button)
isEnabled = false
DispatchQueue.main.asyncAfter(deadline: .now() + actionDelay) { [weak self] in
print("恢復(fù)時(shí)間\(Date())")
self?.isEnabled = true
}
}
/// 添加點(diǎn)擊事件
func addAction(_ delay: TimeInterval = 0, action: @escaping ActionBlock) {
addTarget(self, action: #selector(btnDelayClick(_:)) , for: .touchUpInside)
actionDelay = delay
actionBlock = action
}
}
調(diào)用方法
button.addAction(2) {
print("2秒后才能繼續(xù)點(diǎn)擊")
}