美文网首页程序员我看人间事,热爱作首诗
Swift:通过Closure设置UIButton的action

Swift:通过Closure设置UIButton的action

作者: 泪已无痕 | 来源:发表于2018-05-28 21:05 被阅读14次

    通常情况下,我们需要响应UIButton中的点击事件,一般的做法是:

    let button = UIButton()
    button.addTarget(self, action: #selector(onClicked), for: .touchUpInside)
    
    @objc func onClicked() {
    }
    

    上面的实现给人的感觉不是很符合Swift所提倡的编程范式,所以这里提供一个通过Closure的方式来设置UIButton的action响应事件:

    import UIKit
    
    typealias UIButtonClickedListener = (UIButton) -> ()
    
    extension UIButton {
    
        private struct Keys {
            static var clickedListener = "clickedListener"
        }
    
        private var clickedListener: UIButtonClickedListener? {
            get {
                return objc_getAssociatedObject(self, &Keys.clickedListener) as? UIButtonClickedListener
            }
            set(newValue) {
                objc_setAssociatedObject(self, &Keys.clickedListener, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    
        func setOnClickedListener(listener: @escaping UIButtonClickedListener) {
            clickedListener = listener
            addTarget(self, action: #selector(onButtonClicked), for: .touchUpInside)
        }
    
        @objc func onButtonClicked() {
            if let listener = self.clickedListener {
                listener(self)
            }
        }
    }
    
    let button = UIButton()
    button.setOnClickedListener { print("hello world") }
    

    相关文章

      网友评论

        本文标题:Swift:通过Closure设置UIButton的action

        本文链接:https://www.haomeiwen.com/subject/mqjnjftx.html