Using tableView function scrollToRow it crashed

Viewed 295

When a tableView is scrolling I update dataSource and invoke tableView function reloadData. After tableView DidEndDecelerating I invoke the function:

let indexPath = IndexPath(row: row, section: 0)
if row < dataModels.count {
   tableView.scrollToRow(at: indexPath, at: .top, animated: true)
}

Sometimes it will crash. The crash log likes below:

0 CoreFoundation  __exceptionPreprocess

1 libobjc.A.dylib objc_exception_throw

2 CoreFoundation +[_CFXNotificationTokenRegistration keyCallbacks]

3 Foundation -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:]

4 UIKitCore -[UITableViewRowData _assertValidIndexPath:allowEmptySection:]

5 UIKitCore -[UITableViewRowData ensureHeightsFaultedInForScrollToIndexPath:withScrollPosition:boundsHeight:]

6 UIKitCore -[UITableView _contentOffsetForScrollingToRowAtIndexPath:atScrollPosition:usingPresentationValues:]

7 UIKitCore -[UITableView _scrollToRowAtIndexPath:atScrollPosition:animated:usingPresentationValues:]

8 UIKitCore -[UITableView scrollToRowAtIndexPath:atScrollPosition:animated:]
1 Answers

First check the indexpath is exist or not. The call scrollToRow method.

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


func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    if !scrollView.isDecelerating {
        let indexPath = IndexPath(row: row, section: 0)
        if tableView.isExist(indexPath: indexPath) {
          tableView.scrollToRow(at: indexPath, at: .top, animated: true)
        }
    }
}
Related