我正在尝试在 TableView 中添加一些行。当在屏幕上的行上方插入行时, TableView 会向上跳跃。我希望我的 TableView 保持在当我在上面插入行时已经所在的位置。 请记住: tableView 跳转到它所显示的 indexPath,但在添加上面的行之后,底部行的 indexPaths 会发生变化,并且新的第 n 个 indexPath 是另外的东西。
最佳答案
不幸的是,这并不像人们想象的那么容易。当您在顶部添加单元格时, TableView 会跳转,因为偏移量会保留并且单元格会更新。因此,从某种意义上说,跳跃的不是表格 View ,而是单元格跳跃,因为您在顶部添加了一个新的单元格,这是有意义的。您想要做的是让您的表格 View 随着添加的单元格一起跳转。
我希望您有固定或计算的行高,因为使用自动尺寸会使事情变得相当复杂。行的估计高度与实际高度相同非常重要。就我而言,我只是使用:
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 72.0
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 72.0
}
然后,出于测试目的,每当按下任何单元格时,我都会在顶部添加一个新单元格:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
var offset = tableView.contentOffset.y
cellCount += 1
tableView.reloadData()
let paths = [IndexPath(row: 0, section: 0)]
paths.forEach { path in
offset += self.tableView(tableView, heightForRowAt: path)
}
DispatchQueue.main.async {
tableView.setContentOffset(CGPoint(x: 0.0, y: offset), animated: false)
}
}
所以我保存了 TableView 的当前偏移量。然后我修改数据源(我的数据源仅显示单元格数量)。然后只需重新加载表格 View 即可。
我抓取所有已添加的索引路径,并通过添加每个添加的单元格的预期高度来修改偏移量。
最后我应用新的内容偏移量。在下一个运行循环中执行此操作很重要,通过在主队列上异步分派(dispatch)它可以轻松完成。
至于自动尺寸。
我不会去那里,但拥有大小缓存应该很重要。
private var sizeCache: [IndexPath: CGFloat] = [IndexPath: CGFloat]()
然后你需要在单元格消失时填充大小缓存:
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
sizeCache[indexPath] = cell.frame.size.height
}
并更改估计高度:
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return sizeCache[indexPath] ?? 50.0
}
此外,在修改偏移量时,您需要使用估计高度:
paths.forEach { path in
offset += self.tableView(tableView, estimatedHeightForRowAt: path)
}
这适用于我的情况,但自动尺寸有时很棘手,所以祝他们好运。
关于ios - 当我在屏幕上的索引路径上方插入行时,UITableView 会跳起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54070173/