防止按钮重复点击 Swift
typealias ActionBlock = ((UIButton)->Void) extension UIButton { private struct AssociatedKeys { static var ActionBlock = "ActionBlock" static var ActionDelay = "ActionDelay" } /// 运行时关联 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 } } /// 点击回调 @objc private func btnDelayClick(_ button: UIButton) { actionBlock?(button) isEnabled = false DispatchQueue.main.asyncAfter(deadline: .now() + actionDelay) { [weak self] in print("恢复时间\(Date())") self?.isEnabled = true } } /// 添加点击事件 func addAction(_ delay: TimeInterval = 0, action: @escaping ActionBlock) { addTarget(self, action: #selector(btnDelayClick(_:)) , for: .touchUpInside) actionDelay = delay actionBlock = action } }
调用方法
button.addAction(2) { print("2秒后才能继续点击") }
在北京的灯中,有一盏是我家的。这个梦何时可以实现?哪怕微微亮。北京就像魔鬼训练营,有能力的留,没能力的走……