【问题标题】:UICollectionView scrollToItemAtIndexPath crash ios 10UICollectionView scrollToItemAtIndexPath 崩溃 ios 10
【发布时间】:2019-04-01 17:19:01
【问题描述】:

我在 iOS 10 上遇到此错误,但在 iOS 11 和 iOS 9 上都可以正常工作。

* 由于未捕获的异常 'NSRangeException' 导致应用程序终止,原因:'* -[__NSArrayM objectAtIndex:]: index 5 beyond bounds [0 .. 4]'

这是我的代码:

let indexPath = IndexPath(row: index, section: 0)

print(indexPath.row) // 5
//here is the problem. I got 6 items in my datasource but looks like collectionView still consider it's only 5.
print(collectionView.numberOfItems(inSection: 0)) // 6

if indexPath.row < collectionView.numberOfItems(inSection: 0) {
    collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}

我在调用 scrollToItem 之前检查了 numberOfItems,但仍然崩溃。有点奇怪,有人遇到过这个问题吗?

【问题讨论】:

    标签: crash


    【解决方案1】:

    这也发生在我身上。似乎 Apple 在 iOS10 上引入了一些修改,在重新加载数据后强制手动 invalidateLayout()。这在 iOS9 上不需要,在 iOS11 上也不需要。所以,要么他们改变了主意,要么这是一个错误:)

    只需拨打invalidateLayout() 即可避免崩溃,如下所示:

    self.collectionView.reloadData()
    self.collectionView.collectionViewLayout.invalidateLayout() // Fix iOS10 crash
    

    【讨论】:

    • 嗯,有道理。谢谢,我稍后试试。
    • 解决了我的问题,谢谢!在 iOS 10.3.1 中测试(iOS 11 不需要它但可以正常工作)
    猜你喜欢
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 2017-05-10
    • 2019-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多