問題描述
Xcode12目前沒有發(fā)布正式版本,但是通過Xcode-Beta版本測試發(fā)現(xiàn),項目中好多 UITableViewCell的子試圖不能點擊或者滑動等手勢響應問題。
通過排查發(fā)現(xiàn)這部分有問題的Cell基本都是直接 cell.addSubView(tempView1)這種方式添加的,通過試圖查看發(fā)現(xiàn)被系統(tǒng)自帶的 cell.contentView` (類名UITableViewCellContentView)遮擋在底部了,所以需要改為 '''cell.contentView.addSubView(tempView1)。
搜了一下項目中有 200多處的位置都是這么寫的,而且分很多不同的組件,兼容工作量很大。
所以通過Runtime簡單暴力的方式快速兼容了,原理就是在所有Cell addSubView()時,通過runtime攔截改為 contentView.addsubview(),Demo代碼如下:
extension UITableViewCell {
class func ios14Bug() {
let sel1 = #selector(UITableViewCell.runtime_addSubview(_:))
let sel2 = #selector(UITableViewCell.addSubview(_:))
let method1 = class_getInstanceMethod(UITableViewCell.self, sel1)!
let method2 = class_getInstanceMethod(UITableViewCell.self, sel2)!
let isDid: Bool = class_addMethod(self, sel2, method_getImplementation(method1), method_getTypeEncoding(method1))
if isDid {
class_replaceMethod(self, sel1, method_getImplementation(method2), method_getTypeEncoding(method2))
} else {
method_exchangeImplementations(method2, method1)
}
}
@objc func runtime_addSubview(_ view: UIView) {
// 判斷不讓 UITableViewCellContentView addSubView自己
// 還需要注意 屏蔽掉一些系統(tǒng)直接添加在Cell上的控件,如 UITableViewCellEditControl、UITableViewCellReorderControl
if view.isKind(of: NSClassFromString("UITableViewCellContentView")!) ||
view.isKind(of: NSClassFromString("UITableViewCellEditControl")!) ||
view.isKind(of: NSClassFromString("UITableViewCellReorderControl")!) {
runtime_addSubview(view)
} else {
self.contentView.addSubview(view)
}
}
}
目前在我們項目中已經(jīng)通過這種方式全局兼容,如果有不妥之處,歡迎大家討論!