当我在屏幕上的indexPaths上方插入行时,UITableView会跳起来



我正试图在表视图中添加一些行。当插入的行位于屏幕上的行之上时,表视图会跳起来。当我在上面插入行时,我希望我的表视图保持在它已经所在的位置请记住:tableView跳转到它显示的indexPath,但在添加上面的行后,底部的行indexPath会发生变化,新的第n个indexPath是其他内容。

不幸的是,这并不像人们想象的那么容易。当您在顶部添加单元格时,表视图会跳转,因为偏移量会保持不变,单元格也会更新。因此,从某种意义上说,不是表视图会跳转,单元格会跳转,因为您在顶部添加了一个新的单元格,这是有意义的。您要做的是使表视图随添加的单元格一起跳转。

我希望你已经固定或计算了行的高度,因为使用自动标注可能会使事情变得相当复杂。行的估计高度与实际高度相同是很重要的。在我的情况下,我只是使用:

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)
}

这适用于我的案例,但自动尺寸有时很棘手,所以祝你好运。

最新更新