老司機(jī),又到周末啦,平時(shí)我們工作中會(huì)寫很多的工具類,但是有一些使用工具類去使用又不是很方便,我們就把它抽取封裝成分類。來 看一下今天要寫的關(guān)于手勢的干貨。
-
以前我們是這樣使用手勢的:
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapClick(tap:))))
func tapClick(tap: UITapGestureRecognizer) {
// 手勢點(diǎn)擊后要執(zhí)行的代碼
}
-
現(xiàn)在用了UIGestureRecognizer+Block,簡單來說,你可以這樣使用 UIGestureRecognizer:
self.messageLabel.addGestureRecognizer(UITapGestureRecognizer(actionBlock: { [unowned self](tap) in
// 要執(zhí)行的代碼
}))
相比較來說:不再需要繁瑣地使用 selector 去實(shí)現(xiàn),也解決了代碼分離的問題。就好像把delegate封裝成了閉包,比如很多人使用的藍(lán)牙框架第三方BabyBluetooth就是這么干的,它對(duì)系統(tǒng)的基于CoreBlueTooth的封裝,內(nèi)部把代理實(shí)現(xiàn)都轉(zhuǎn)變成了Block形式。這樣做的目的是代碼封裝性好,可讀性強(qiáng),易于維護(hù)。
-
實(shí)現(xiàn)詳情如下:
// 封裝的手勢閉包回調(diào)
import UIKit
extension UIGestureRecognizer {
typealias MGGestureBlock = ((Any)->())
// MARK:- RuntimeKey 動(dòng)態(tài)綁屬性
// 改進(jìn)寫法【推薦】用枚舉實(shí)現(xiàn)綁定的key 寫的時(shí)候會(huì)有提示
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 動(dòng)態(tài)地綁成 UIGestureRecognizer 的一個(gè)變量,invoke 的時(shí)候再調(diào)用這個(gè) block。
-
開發(fā)過程中遇到了的坑。
- 我一開始在類方法里面進(jìn)行了動(dòng)態(tài)綁定,錯(cuò)誤代碼如下:
//以下是錯(cuò)誤代碼:
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é)果就是,變量被綁到了這個(gè)類對(duì)象上,因?yàn)樵陬惙椒ɡ锩?self 指的是這個(gè)類對(duì)象,而類對(duì)象是常駐內(nèi)存直到程序退出才釋放的,這也就導(dǎo)致了這個(gè)類上始終綁著第一次的 target,之后無論怎樣都不會(huì)改變。如果恰好你在 block 中有強(qiáng)制持有了 block 外的其他對(duì)象,那就會(huì)導(dǎo)致這些對(duì)象都不會(huì)釋放,造成內(nèi)存泄露。在實(shí)例方法中動(dòng)態(tài)綁定即可解決。
- 如果不使用動(dòng)態(tài)綁定,使用如下的代碼會(huì)產(chǎn)生怎樣的結(jié)果?
//錯(cuò)誤代碼
convenience init(actionBlock block: MGGestureBlock) {
return self.init(target: MGGestureRecognizerBlockTarget(block: block), selector: #selector(self.invoke))
}
結(jié)果就是出了這個(gè)作用域 target 對(duì)象釋放。通過查閱文檔,我在《OC 編程概念》的 Target-Action 一節(jié)中,看到蘋果有提到這么一句: Control objects do not (and should not) retain their targets. 按照慣例,如果有特殊情況,蘋果會(huì)特別提醒(比如 NSTimer 的描述中就寫到 target The timer maintains a strong reference to this object until it (the timer) is invalidated. )。所以 UIGestureRecognizer 是不會(huì)對(duì) target 強(qiáng)引用。一旦出了作用域,target 對(duì)象就釋放了。所以,需要使用動(dòng)態(tài)綁定強(qiáng)制持有。
類似的UIButton也一樣的
extension UIButton {
typealias MGButtonBlock = ((Any)->())
// MARK:- RuntimeKey 動(dòng)態(tài)綁屬性
// 改進(jìn)寫法【推薦】
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)
}
}