简体   繁体   English

使用 tableView function scrollToRow 它崩溃了

[英]Using tableView function scrollToRow it crashed

When a tableView is scrolling I update dataSource and invoke tableView function reloadData .当 tableView 滚动时,我更新 dataSource 并调用 tableView function reloadData After tableView DidEndDecelerating I invoke the function:在 tableView DidEndDecelerating之后,我调用了 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:]

First check the indexpath is exist or not.首先检查indexpath是否存在。 The call scrollToRow method.调用scrollToRow方法。

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)
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM