美文网首页
Swift给button和view添加block回调

Swift给button和view添加block回调

作者: 一字码 | 来源:发表于2018-06-05 18:13 被阅读42次

    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回调

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