UITableView reloadData contentOffset被改变

项目里有一个类似朋友圈的功能界面,列表上新增了评论后要滚动到相应位置,也有删除评论的功能。遇到的问题就是在修改了数据源后,刷新了界面,但是UITableView的contentOffset会大概率的被改变,不是之前浏览的位置。

由于cell是用约束自动撑开的,所以UITableView的配置如下:

修复方案:

使用字典缓存cell高度:

private var cellHeightsDictionary: [IndexPath: CGFloat] = [:]

UITableView的代理方法:

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        self.cellHeightsDictionary[indexPath] = cell.frame.size.height
    }
    
    func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
        if let height =  self.cellHeightsDictionary[indexPath]{
            return height
        }
        return UITableView.automaticDimension
    }

另外:UITableView reloadData后想要滚动到相应的位置,最好在主线程回调里面调用setContentOffset之类的方法:

tableView.reloadData()

DispatchQueue.main.async {

    // scroll to position
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值