隨著屏幕碎片化,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ì)卡頓??