调用方法
but.addClickEvent(click: { (but) in
print("点击事件")
})
添加扩展方法
typealias butAction = (UIButton)->()
extension UIButton{
private struct butKeys{
static var action = "click"
}
@objc dynamic var click: butAction? {
set{
objc_setAssociatedObject(self,&butKeys.action, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_COPY)
}
get{
if let action = objc_getAssociatedObject(self, &butKeys.action) as? butAction{
return action
}
return nil
}
}
func addClickEvent(click:@escaping butAction) {
self.click = click
self.addTarget(self, action: #selector(touchUpInSideFun), for: UIButton.Event.touchUpInside)
}
@objc func touchUpInSideFun(but: UIButton) {
if let click = self.click {
click(but)
}
}
}