How to scroll UITableView to a row *safely*?
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)
}
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)
}