Swift给button和view添加block回调

UIButton-E.swift

extension UIButton {
private struct RuntimeKey {
static let actionBlock = UnsafeRawPointer.init(bitPattern: "actionBlock".hashValue)
}

var callBack: buttonClickBlock? {
    get {
        return objc_getAssociatedObject(self, UIButton.RuntimeKey.actionBlock!) as? buttonClickBlock
    }
    set {
        objc_setAssociatedObject(self, UIButton.RuntimeKey.actionBlock!, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
}
convenience init(type:UIButtonType) {
    self.init()
    self.addTarget(self, action: #selector(tapped(button:)), for: .touchUpInside)
}

@objc func tapped(button:UIButton){
    if self.callBack != nil {
        self.callBack!()
    }
}

}

UIView-E.swift

import UIKit

typealias viewClick = (() -> ())

extension UIView {
private struct RuntimeKey {
static let actionBlock = UnsafeRawPointer.init(bitPattern: "actionBlock".hashValue)
static let actionBlock2 = UnsafeRawPointer.init(bitPattern: "actionBlock2".hashValue)
}

var viewCallBack : viewClick? {
    get {
        return objc_getAssociatedObject(self, UIButton.RuntimeKey.actionBlock!) as? buttonClickBlock
    }
    set {
        objc_setAssociatedObject(self, UIButton.RuntimeKey.actionBlock!, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        setUpViewClick()
    }
    
}

@objc func tapView() {
    if self.viewCallBack != nil {
        self.viewCallBack!()
    }
}

func setUpViewClick() {
    let gesture = UITapGestureRecognizer.init(target: self, action: #selector(tapView))
    
    self.addGestureRecognizer(gesture)
}

}

你可能感兴趣的:(Swift给button和view添加block回调)