Cell高度自适应和UITable跳动问题

随着屏幕碎片化,UI布局使用Autolayout越来越流行。特别是Cell的高度自适应,如果用frame会非常麻烦,如果用xib创建,设置好约束,设置UITable的属性,便可以自适应高度。只需要下面几行代码:

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

只要设置好约束,这两行代码便可以自适应Cell高度了。
iOS11里,estimatedRowHeight属性默认为UITableViewAutomaticDimension,rowHeight默认也是UITableViewAutomaticDimension,另外还有estimatedSectionHeaderHeight和estimatedSectionFooterHeight,设置为0便可以禁止自动估算,防止出现乱七八糟的BUG。

但是这样设置以后,在上拉加载reload数据的时候,会出现跳动问题,这个时候,需要缓存一下估算的高度,防止跳动。因为我的项目里引入了YYKit,所以我就用YYCache来做缓存了。

//VC里声明一个cache属性
var cache = YYCache.init(name: "HVC")
//在即将展示cell时,根据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)
    }
//然后在返回估算高度的代理里边,判断是否已经估算完成,如果有,就直接返回高度,防止跳动
    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来自适应Cell高度了,并且还可以提高流畅度。iOS12修改了Autolayout的算法,随着view的增加,并不会导致界面卡顿,可以放心使用了。

其实最后我想说一句,只要你的手机够好,一般不会卡顿

你可能感兴趣的:(Cell高度自适应和UITable跳动问题)