Swift 在UIButton扩展中添加 block 点击事件

Swift 在UIButton扩展中添加 block 点击事件,第1张

直接看代码,代码中有详细注释

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/993191.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存