Search code examples
iosswiftuitableviewswift3nsindexpath

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


I have a method that scrolls my UITableView to the bottom:

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)

    })
}

it worked well before, however when I added Header View - it crashes.

I see in the console:

8
1
[1, 8]
it will crash now

so I do not understand why this line:

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

causes crash. What am I missing here?


Solution

  • You have problem with this

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

    Try doing -1

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