我们ui搭建中经常要为UIButton或UIImageVIew添加点击的事件。而点击事件要放在另一个方法上处理,看着就很不爽,所以就想用闭包方式处理了。使用如下:
view.addSubview(button)
button.addAction { (button) in
print("click button")
}
view.addSubview(button2)
button2.addAction {[weak self] (button) in
guard let ws = self else {return}//防止使用self循环引用
print("click button2")
}
view.addSubview(imageView)
imageView.addAction { (imageView) in
print("click imageView")
}
emailField.textChangeAction { (field) in
print("textChange")
}
具体的扩展代码如下:
fileprivate typealias buttonClick = ((UIButton)->())
extension UIButton {
@objc private func clickAction() {
self.actionBlock?(self)
}
private struct RuntimeKey {
static let actionBlock = UnsafeRawPointer.init(bitPattern: "actionBlock".hashValue)
}
private var actionBlock: buttonClick? {
set {
objc_setAssociatedObject(self, UIButton.RuntimeKey.actionBlock!, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, UIButton.RuntimeKey.actionBlock!) as? buttonClick
}
}
func addAction(controlEvents: UIControl.Event = .touchUpInside ,handle:@escaping ((UIButton)->())) {
self.actionBlock = handle
self.addTarget(self, action: #selector(clickAction), for: controlEvents)
}
}
fileprivate typealias imageClick = ((UIImageView)->())
extension UIImageView {
@objc private func clickAction() {
self.actionBlock?(self)
}
private struct RuntimeKey {
static let actionBlock = UnsafeRawPointer.init(bitPattern: "actionBlock".hashValue)
}
private var actionBlock: imageClick? {
set {
objc_setAssociatedObject(self, UIImageView.RuntimeKey.actionBlock!, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, UIImageView.RuntimeKey.actionBlock!) as? imageClick
}
}
func addAction(handle:@escaping ((UIImageView)->())) {
self.actionBlock = handle
self.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(clickAction))
self.addGestureRecognizer(tap)
}
}
fileprivate typealias TextFieldChange = ((UITextField)->())
extension UITextField {
@objc private func changeAction() {
self.actionBlock?(self)
}
private struct RuntimeKey {
static let actionBlock = UnsafeRawPointer.init(bitPattern: "actionBlock".hashValue)
}
private var actionBlock: TextFieldChange? {
set {
objc_setAssociatedObject(self, UITextField.RuntimeKey.actionBlock!, newValue, .OBJC_ASSOCIATION_COPY_NONATOMIC)
}
get {
return objc_getAssociatedObject(self, UITextField.RuntimeKey.actionBlock!) as? TextFieldChange
}
}
func textChangeAction(handle:@escaping ((UITextField)->())) {
self.actionBlock = handle
self.addTarget(self, action: #selector(changeAction), for: UIControl.Event.editingChanged)
}
}
完
网友评论