[英]UITableView add rows and scroll to bottom
我正在编写一个表视图,其中在用户交互时添加行。 一般行为只是添加一行,然后滚动到表的末尾。
这在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
对象链接这些函数,但这完全CATransaction
了在其他地方定义的异步完成块更新一些单元格UI元素的代码。
所以任何帮助将不胜感激:)
我设法通过在调整insets之前调用self.tableView.layoutIfNeeded()
来解决问题:
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.tableView.endUpdates()
self.tableView.layoutIfNeeded()
self.adjustInsets()
self.tableView.scrollToRow(at: lastIndexPath,
at: UITableViewScrollPosition.bottom,
animated: true)
}
}
确保您尊重安全区域。 有关更多详细信息,请访问: https : //developer.apple.com/ios/update-apps-for-iphone-x/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.