直接看代码,代码中有详细注释
extension UIButton {
// 定义关联的Key
private struct UIButtonKeys {
static var clickKey = "UIButton+Extension+ActionKey"
}
func addActionWithBlock(_ closure: @escaping (_ sender:UIButton)->()) {
//把闭包作为一个值 先保存起来
objc_setAssociatedObject(self, &UIButtonKeys.clickKey, closure, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
//给按钮添加传统的点击事件,调用写好的方法
self.addTarget(self, action: #selector(my_ActionForTapGesture), for: .touchUpInside)
}
@objc private func my_ActionForTapGesture() {
//获取闭包值
let obj = objc_getAssociatedObject(self, &UIButtonKeys.clickKey)
if let action = obj as? (_ sender:UIButton)->() {
//调用闭包
action(self)
}
}
}
使用测试:
lazy var codeBtn: UIButton = {
let btn = UIButton(frame: CGRect.init(x: 100, y: 100, width: 200, height: 50))
btn.backgroundColor = .white
btn.setTitle("验证码1", for: .normal)
btn.tag = 10081
btn.setTitleColor(.lightGray, for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
btn.addActionWithBlock { btn in
printLog("btn == \(String(describing: btn.currentTitle))")
printLog("btn.tag == \(btn.tag)")
}
return btn
}()
lazy var codeBtn1: UIButton = {
let btn = UIButton(frame: CGRect.init(x: 100, y: 200, width: 200, height: 50))
btn.backgroundColor = .white
btn.setTitle("验证码2", for: .normal)
btn.tag = 10082
btn.setTitleColor(.lightGray, for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
btn.addActionWithBlock { btn in
printLog("btn == \(String(describing: btn.currentTitle))")
printLog("btn.tag == \(btn.tag)")
}
return btn
}()
//点击按钮 打印结果
2022-03-17 11:31:06.052000 TestFristController.swift -> codeBtn [第26行] btn == Optional("验证码1")
2022-03-17 11:31:06.055000 TestFristController.swift -> codeBtn [第27行] btn.tag == 10081
2022-03-17 11:31:07.603000 TestFristController.swift -> codeBtn1 [第39行] btn == Optional("验证码2")
2022-03-17 11:31:07.604000 TestFristController.swift -> codeBtn1 [第40行] btn.tag == 10082
传统点击事件addTarget依然可以用
END
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)