首页 > 解决方案 > UICollectionView scrollToItemAtIndexPath 崩溃 ios 10

问题描述

我在 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

解决方案


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

只需调用invalidateLayout()以避免崩溃,如下所示:

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

推荐阅读