我正在尝试在表格视图中添加一些行。当在屏幕上的行上方插入行时,表格视图会跳起来。我希望我的表格视图保持在上面插入行时的位置。 请紧记::tableView跳转到它显示的indexPath,但是在上面添加了行之后,最下面的行indexPaths发生了变化,而新的第n个indexPath则有所不同。
答案 0 :(得分:0)
不幸的是,这并不是一件容易的事。当您在顶部添加单元格时,表视图会跳转,因为偏移量会持久存在并更新单元格。因此从某种意义上说,并不是表格视图在跳动,而是单元格在跳动,因为您在顶部添加了一个新的视图才有意义。您要做的是使表格视图与添加的单元格一起跳转。
我希望您具有固定的或计算的行高,因为使用自动尺寸标注会使事情变得相当复杂。具有与行的实际高度相同的估计高度很重要。就我而言,我只是使用:
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)
}
}
因此,我保存表视图的当前偏移量。然后,我修改数据源(我的数据源仅显示单元格数)。然后,只需重新加载表格视图即可。
我抓住所有已添加的索引路径,并通过添加每个添加的单元格的预期高度来修改偏移量。
最后,我应用新的内容偏移量。而且,在下一个运行循环中执行此操作很重要,这是通过在主队列上异步调度它来轻松实现的。
关于自动尺寸。
我不会去那里,但是拥有大小缓存应该很重要。
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)
}
这对我来说很有效,但是自动标注有时会很棘手,所以祝他们好运。