简体   繁体   English

UITableView添加行并滚动到底部

[英]UITableView add rows and scroll to bottom

I'm writing a table view where rows are added upon user interaction. 我正在编写一个表视图,其中在用户交互时添加行。 The general behavior is simply to add a single row, then scroll to the end of the table. 一般行为只是添加一行,然后滚动到表的末尾。

This was working perfectly fine before iOS11, but now the scrolling always jumps from the top of the table instead of smoothly scrolling. 这在iOS11之前工作得非常好,但现在滚动总是从表顶部跳转而不是平滑滚动。

Here's the code that has to do with adding new rows: 这是与添加新行有关的代码:

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

And

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

I'm confident the error lies within the fact that multiple UI updates are pushed at the same time (adding row and recalculating edge insets), and tried chaining these functions with separate CATransaction objects, but that completely messes up asynchronous completion blocks defined elsewhere in the code which update some of the cell's UI elements. 我确信错误在于同时推送多个UI更新(添加行和重新计算边缘插入)这一事实,并尝试使用单独的CATransaction对象链接这些函数,但这完全CATransaction了在其他地方定义的异步完成块更新一些单元格UI元素的代码。

So any help would be appreciated :) 所以任何帮助将不胜感激:)

I managed to fix the issue by simply just calling self.tableView.layoutIfNeeded() before adjusting the insets: 我设法通过在调整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)
    }
}

Make sure that you are respecting the Safe Areas. 确保您尊重安全区域。 For more details, check: https://developer.apple.com/ios/update-apps-for-iphone-x/ 有关更多详细信息,请访问: https//developer.apple.com/ios/update-apps-for-iphone-x/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM