通常情况下,我们需要响应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") }
网友评论