我的 tableView 中有动态单元格高度
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 100
我想做与 whatsapp 应用程序相同的事情(分页),我想加载 25 x 25 行,所以当用户在顶部滚动时,我想加载新数据但我想保持相同的滚动位置,这就是我做了
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isMore && scrollView.contentOffset.y == 0 {
loadMore() // function that add new data in my model
self.tableView.reloadData()
}
}
我遇到的问题是在我到达我的 tableview 顶部后它调用 reloadData 但 tableView 滚动到 UP
我像这样测试了一些其他解决方案:
var cellHeights: [IndexPath : CGFloat] = [:]
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cellHeights[indexPath] = cell.frame.size.height
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
guard let height = cellHeights[indexPath] else { return 70.0 }
return height
}
还是不行
最佳答案
如果您正在重新加载表格以添加更多数据,则在重新加载后调用下面的函数以保留滚动位置。
tableview.scrollToRow(at: indexPath, at: .middle, animated: true)
这里的indexPath是reload前最后一个cell的indexPath。
关于ios - 调用 reloadData 后 UITableView 动态单元格高度滚动到顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44112183/