项目里有一个类似朋友圈的功能界面,列表上新增了评论后要滚动到相应位置,也有删除评论的功能。遇到的问题就是在修改了数据源后,刷新了界面,但是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
}
博客内容讨论了在iOS开发中,面对UITableView在数据源更新后内容偏移的问题。作者提出了一种解决方案,通过缓存cell的高度并在数据刷新后调整contentOffset来保持浏览位置。此外,还强调了在主线程中调用setContentOffset以确保滚动操作的正确执行。
8629

被折叠的 条评论
为什么被折叠?



