Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITableView indexPath of last row

I am attempting to make the last row in a UITableView visible, after it has been added. Right now, when I add a row and call reloadData, the table goes to the top.

I figure if I get the indexPath for the last row, that I can select that row and it should appear in the list. I am unsure of how to get that value, or even if I am approaching this correctly.

How do I get an indexPath for a specific row?

like image 730
Scott Kilbourn Avatar asked Jul 09 '15 04:07

Scott Kilbourn


1 Answers

Shamsudheen TK's answer will crash

if there is no rows/sections in tableview.

The following solution to avoid crash at run time

extension UITableView {
  func scrollToBottom() {

    let lastSectionIndex = self.numberOfSections - 1
    if lastSectionIndex < 0 { //if invalid section
        return
    }

    let lastRowIndex = self.numberOfRows(inSection: lastSectionIndex) - 1
    if lastRowIndex < 0 { //if invalid row
        return
    }

    let pathToLastRow = IndexPath(row: lastRowIndex, section: lastSectionIndex)
    self.scrollToRow(at: pathToLastRow, at: .bottom, animated: true)
  }
}

Note: If you are trying to scroll to bottom in block/clousure then you need to call this on main thread.

DispatchQueue.main.async {
  self.tableView.scrollToBottom()
}

Hope this will helps other

like image 64
Mahendra Avatar answered Sep 19 '22 15:09

Mahendra