MG--Swift3.0 好用的分類


老司機,又到周末啦,平時我們工作中會寫很多的工具類,但是有一些使用工具類去使用又不是很方便,我們就把它抽取封裝成分類。來 看一下今天要寫的關(guān)于手勢的干貨。

  • 以前我們是這樣使用手勢的:

self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapClick(tap:))))
func tapClick(tap: UITapGestureRecognizer) {
      // 手勢點擊后要執(zhí)行的代碼  
}
  • 現(xiàn)在用了UIGestureRecognizer+Block,簡單來說,你可以這樣使用 UIGestureRecognizer:

self.messageLabel.addGestureRecognizer(UITapGestureRecognizer(actionBlock: { [unowned self](tap) in
      // 要執(zhí)行的代碼
 }))

相比較來說:不再需要繁瑣地使用 selector 去實現(xiàn),也解決了代碼分離的問題。就好像把delegate封裝成了閉包,比如很多人使用的藍牙框架第三方BabyBluetooth就是這么干的,它對系統(tǒng)的基于CoreBlueTooth的封裝,內(nèi)部把代理實現(xiàn)都轉(zhuǎn)變成了Block形式。這樣做的目的是代碼封裝性好,可讀性強,易于維護。


  • 實現(xiàn)詳情如下:

//  封裝的手勢閉包回調(diào)
import UIKit
extension UIGestureRecognizer {
    typealias MGGestureBlock = ((Any)->())
    // MARK:- RuntimeKey   動態(tài)綁屬性
    // 改進寫法【推薦】用枚舉實現(xiàn)綁定的key 寫的時候會有提示
    fileprivate struct RuntimeKey {
        static let mg_GestureBlockKey = UnsafeRawPointer.init(bitPattern: "mg_GestureBlockKey".hashValue)
        /// ...其他Key聲明
    }
    // 便利構(gòu)造方法
    convenience init(actionBlock: @escaping MGGestureBlock) {
        self.init()
        addActionBlock(actionBlock)
        addTarget(self, action: #selector(invoke(_:)))
    }
    // 內(nèi)部方法 加上fileprivat防止外界直接調(diào)用
    fileprivate func addActionBlock(_ block: MGGestureBlock?) {
        if (block != nil) {
            objc_setAssociatedObject(self, UIGestureRecognizer.RuntimeKey.mg_GestureBlockKey, block!, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    // 內(nèi)部方法
    @objc fileprivate func invoke(_ sender: Any) {
        let block = objc_getAssociatedObject(self, UIGestureRecognizer.RuntimeKey.mg_GestureBlockKey) as? MGGestureBlock
        if (block != nil) {
            block!(sender);
        }
    }
}
  • 原理就是把 block 動態(tài)地綁成 UIGestureRecognizer 的一個變量,invoke 的時候再調(diào)用這個 block。




  • 開發(fā)過程中遇到了的坑。

  • 我一開始在類方法里面進行了動態(tài)綁定,錯誤代碼如下:
//以下是錯誤代碼:
convenience init(actionBlock block: MGGestureBlock) {
    return self.init(target: self.gestureRecognizerBlockTarget(block), selector: #selector(self.invoke))
}

class func gestureRecognizerBlockTarget(_ block: MGGestureBlock) -> MGGestureRecognizerBlockTarget {
    var target: MGGestureRecognizerBlockTarget? = objc_getAssociatedObject(self, target_key)
    if target == nil {
        target = MGGestureRecognizerBlockTarget(block: block)
        objc_setAssociatedObject(self, target_key, target, OBJC_ASSOCIATION_RETAIN_NONATOMIC)
    }
    return target!
}

這樣導(dǎo)致的結(jié)果就是,變量被綁到了這個類對象上,因為在類方法里面 self 指的是這個類對象,而類對象是常駐內(nèi)存直到程序退出才釋放的,這也就導(dǎo)致了這個類上始終綁著第一次的 target,之后無論怎樣都不會改變。如果恰好你在 block 中有強制持有了 block 外的其他對象,那就會導(dǎo)致這些對象都不會釋放,造成內(nèi)存泄露。在實例方法中動態(tài)綁定即可解決。


  • 如果不使用動態(tài)綁定,使用如下的代碼會產(chǎn)生怎樣的結(jié)果?
//錯誤代碼
convenience init(actionBlock block: MGGestureBlock) {
    return self.init(target: MGGestureRecognizerBlockTarget(block: block), selector: #selector(self.invoke))
}

結(jié)果就是出了這個作用域 target 對象釋放。通過查閱文檔,我在《OC 編程概念》的 Target-Action 一節(jié)中,看到蘋果有提到這么一句: Control objects do not (and should not) retain their targets. 按照慣例,如果有特殊情況,蘋果會特別提醒(比如 NSTimer 的描述中就寫到 target The timer maintains a strong reference to this object until it (the timer) is invalidated. )。所以 UIGestureRecognizer 是不會對 target 強引用。一旦出了作用域,target 對象就釋放了。所以,需要使用動態(tài)綁定強制持有。




類似的UIButton也一樣的

extension UIButton {
    typealias MGButtonBlock = ((Any)->())
    // MARK:- RuntimeKey   動態(tài)綁屬性
    // 改進寫法【推薦】
    fileprivate struct RuntimeKey {
        static let mg_BtnBlockKey = UnsafeRawPointer.init(bitPattern: "mg_BtnBlockKey".hashValue)
        /// ...其他Key聲明
    }
    
    convenience init(actionBlock: @escaping MGButtonBlock) {
        self.init()
        addActionBlock(actionBlock)
        addTarget(self, action: #selector(invoke(_:)), for: .touchUpInside)
    }
    
    fileprivate func addActionBlock(_ block: MGButtonBlock?) {
        if (block != nil) {
            objc_setAssociatedObject(self, UIButton.RuntimeKey.mg_BtnBlockKey, block!, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    @objc fileprivate func invoke(_ sender: Any) {
        let block = objc_getAssociatedObject(self, UIButton.RuntimeKey.mg_BtnBlockKey) as? MGButtonBlock
        if (block != nil) {
            block!(sender);
        }
    }
    
    convenience init(imageName: UIImage, title: String,actionBlock: @escaping MGButtonBlock) {
        self.init(actionBlock: actionBlock)
        // 1.設(shè)置按鈕的屬性
        setImage(imageName, for: .normal)
        setTitle(title, for: UIControlState.normal)
        titleLabel?.font = UIFont.systemFont(ofSize: 14)
        setTitleColor(UIColor.darkGray, for: UIControlState.normal)
        sizeToFit()
    }
    
    convenience init(title: String,actionBlock: @escaping MGButtonBlock) {
        self.init(actionBlock: actionBlock)
        // 1.設(shè)置按鈕的屬性
        setTitle(title, for: UIControlState.normal)
        titleLabel?.font = UIFont.systemFont(ofSize: 14)
        setTitleColor(UIColor.darkGray, for: UIControlState.normal)
        sizeToFit()
    }
    
    convenience init(norImage:UIImage,pressImage: UIImage,actionBlock: @escaping MGButtonBlock) {
        self.init(actionBlock: actionBlock)
        // 1.設(shè)置按鈕的屬性
        setImage(norImage, for: .normal)
        setImage(pressImage, for: .highlighted)
    }
    
    convenience init(norImage:UIImage,selectedImage: UIImage,actionBlock: @escaping MGButtonBlock) {
        self.init(actionBlock: actionBlock)
        // 1.設(shè)置按鈕的屬性
        setImage(norImage, for: .normal)
        setImage(selectedImage, for: .selected)
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容