添加 header 视图后,滚动到 UITableView 的底部导致 NSException

After adding header view, scroll to bottom of UITableView cause NSException

我有一个方法可以将 UITableView 滚动到底部:

func tableViewScrollToBottom(_ animated: Bool) {

    let delay = 0.1 * Double(NSEC_PER_SEC)
    let time = DispatchTime.now() + Double(Int64(delay)) / Double(NSEC_PER_SEC)

    DispatchQueue.main.asyncAfter(deadline: time, execute: {
        print(self.tview.numberOfRows(inSection: 0))
        print(self.tview.numberOfSections)
        let indexPath = IndexPath(row: self.tview.numberOfRows(inSection: 0), section: self.tview.numberOfSections)
        print(indexPath)
        print("it will crash now")
        self.tview.scrollToRow(at: indexPath, at: .bottom, animated: animated)

    })
}

它以前运行良好,但是当我添加 Header 视图时 - 它崩溃了。

我在控制台看到:

8
1
[1, 8]
it will crash now

所以我不明白为什么这一行:

self.tview.scrollToRow(at: indexPath, at: .bottom, animated: animated)

导致崩溃。我在这里错过了什么?

你对此有疑问

let indexPath = IndexPath(row: self.tview.numberOfRows(inSection: 0), section: self.tview.numberOfSections)

尝试做-1

let indexPath = IndexPath(row: self.tview.numberOfRows(inSection: 0)-1, section: self.tview.numberOfSections-1)