iOS14 UITableViewCell 問題

問題描述

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)通過這種方式全局兼容,如果有不妥之處,歡迎大家討論!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

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