簡體   English   中英

UITableView添加行並滾動到底部

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM