Cell高度自適應(yīng)和UITable跳動(dòng)問題

隨著屏幕碎片化,UI布局使用Autolayout越來越流行。特別是Cell的高度自適應(yīng),如果用frame會(huì)非常麻煩,如果用xib創(chuàng)建,設(shè)置好約束,設(shè)置UITable的屬性,便可以自適應(yīng)高度。只需要下面幾行代碼:

        self.tableView.estimatedRowHeight = 200
        self.tableView.rowHeight = UITableViewAutomaticDimension
        self.tableView.estimatedSectionFooterHeight = 0
        self.tableView.estimatedSectionHeaderHeight = 0

只要設(shè)置好約束,這兩行代碼便可以自適應(yīng)Cell高度了。
iOS11里,estimatedRowHeight屬性默認(rèn)為UITableViewAutomaticDimension,rowHeight默認(rèn)也是UITableViewAutomaticDimension,另外還有estimatedSectionHeaderHeight和estimatedSectionFooterHeight,設(shè)置為0便可以禁止自動(dòng)估算,防止出現(xiàn)亂七八糟的BUG。

但是這樣設(shè)置以后,在上拉加載reload數(shù)據(jù)的時(shí)候,會(huì)出現(xiàn)跳動(dòng)問題,這個(gè)時(shí)候,需要緩存一下估算的高度,防止跳動(dòng)。因?yàn)槲业捻?xiàng)目里引入了YYKit,所以我就用YYCache來做緩存了。

//VC里聲明一個(gè)cache屬性
var cache = YYCache.init(name: "HVC")
//在即將展示cell時(shí),根據(jù)model的id來緩存一下高度
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        let model = self.pageLists[indexPath.section]
        
        self.cache?.setObject(cell.frame.size.height as NSCoding, forKey: (model.id ?? 0).description)
    }
//然后在返回估算高度的代理里邊,判斷是否已經(jīng)估算完成,如果有,就直接返回高度,防止跳動(dòng)
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let model = self.pageLists[indexPath.section]
        
        if let height = self.cache?.object(forKey: (model.id ?? 0).description) as? CGFloat{
            
            return height
        }else{
            
            return UITableViewAutomaticDimension
        }
    }

以上一頓操作,就可以完美的使用Xib來自適應(yīng)Cell高度了,并且還可以提高流暢度。iOS12修改了Autolayout的算法,隨著view的增加,并不會(huì)導(dǎo)致界面卡頓,可以放心使用了。

其實(shí)最后我想說一句,只要你的手機(jī)夠好,一般不會(huì)卡頓??

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

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

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