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.
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.
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.
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)
}
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With