ios - 调用 reloadData 后 UITableView 动态单元格高度滚动到顶部

标签 ios swift uitableview

我的 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/

相关文章:

android - TextField 输入始终以大写开头

ios - UIAlertView 用于在搜索中找不到匹配项

ios - 苹果商店的 Dose Flurry SDK 支持

ios - 不支持推送导航 Controller - 自 Xcode 6.2 更新以来

ios - iPhone SDK 系统提供的按钮和图标

ios - 为什么在 subview 中添加 UILabel 会使其像素化

ios - Swift - 二元运算符不能应用于类型的操作数

SWIFT URL 字符串构建

ios - UITableView 中的 self.delegate=self,有什么问题吗?

ios - UITableView 滚动时数据消失?