我正在写一个表视图,在用户交互时添加行。一般行为仅仅是添加一行,然后滚动到表的结尾。UITableView添加行并滚动到底部
这在iOS11之前工作得很好,但现在滚动总是从表顶部跳转而不是平滑滚动。
下面是与添加新行做代码:
func updateLastRow() {
DispatchQueue.main.async {
let lastIndexPath = IndexPath(row: self.currentSteps.count - 1, section: 0)
self.tableView.beginUpdates()
self.tableView.insertRows(at: [lastIndexPath], with: .none)
self.adjustInsets()
self.tableView.endUpdates()
self.tableView.scrollToRow(at: lastIndexPath,
at: UITableViewScrollPosition.none,
animated: true)
}
}
而且
func adjustInsets() {
let tableHeight = self.tableView.frame.height + 20
let table40pcHeight = tableHeight/100 * 40
let bottomInset = tableHeight - table40pcHeight - self.loadedCells.last!.frame.height
let topInset = table40pcHeight
self.tableView.contentInset = UIEdgeInsetsMake(topInset, 0, bottomInset, 0)
}
我相信错误在于一个事实,即多个UI更新是在同一推中(添加行和重新计算边缘插入),并尝试将这些函数与单独的CATransaction
对象链接起来,但这会完全混淆代码中用于更新某些单元的UI元素的其他位置定义的异步完成块。
所以,任何帮助将不胜感激:)
GENIUS! layoutIfNeeded是必须的! –