Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll UITableView to a row *safely*?

Sometimes when I tried to scroll a tableview to a row, I can unexpectedly supply a nonexistent section/row. And then the app will crash.

self.tableView.scrollToRow(at: IndexPath(row: targetRow, section: targetSection), at: UITableViewScrollPosition.bottom, animated: true);

How can I make this scrolling process crash-safe? I mean, if I do supply a nonexistent section/row, I want UITableView just ignore it. Or how can I check whether a section/row is exist or not within a UITableView before I do the scroll? Thanks.

like image 622
Chen Li Yong Avatar asked Sep 29 '17 07:09

Chen Li Yong


People also ask

How to scroll to top UITableVIew swift?

To scroll to the top of our tableview we need to create a new IndexPath . This index path has two arguments, row and section . All we want to do is scroll to the top of the table view, therefore we pass 0 for the row argument and 0 for the section argument. UITableView has the scrollToRow method built in.

Is UITableVIew scrollable?

Smooth Scrolling:- As a result, it affects the smoother scrolling experience. In UITableVIew, Scrolling will be smooth through cell reuse with the help of prepareForReuse() method.


2 Answers

Use this UITableView extension to check whether a Indexpath is valid.

extension UITableView
{
    func indexPathExists(indexPath:IndexPath) -> Bool {
        if indexPath.section >= self.numberOfSections {
            return false
        }
        if indexPath.row >= self.numberOfRows(inSection: indexPath.section) {
            return false
        }
        return true
    }
}

Use like this

var targetRowIndexPath = IndexPath(row: 0, section: 0)
if table.indexPathExists(indexPath: targetRowIndexPath)
{
  table.scrollToRow(at: targetRowIndexPath, at: .bottom, animated: true)
}
like image 169
RajeshKumar R Avatar answered Sep 24 '22 22:09

RajeshKumar R


Try this --

let indexPath = IndexPath(row: targetRow, section: targetSection)
if let _ = self.tableView.cellForRow(at: indexPath) {
 self.tableView.scrollToRow(at: indexPath, at: UITableViewScrollPosition.bottom, animated: true)
}
like image 41
Aditya Srivastava Avatar answered Sep 23 '22 22:09

Aditya Srivastava