UICollectionView scrollToItemAtIndexPath 崩溃 ios 10
UICollectionView scrollToItemAtIndexPath crash ios 10
我在 iOS 10 上遇到了这个错误,但它在 iOS 11 和 iOS 9 上都工作正常。
* 由于未捕获的异常 'NSRangeException' 而终止应用程序,原因:'* -[__NSArrayM objectAtIndex:]:索引 5 超出范围 [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,但仍然崩溃。有点奇怪,以前有人遇到过这个问题吗?
我也遇到过。 Apple 似乎对 iOS10 进行了一些修改,强制在重新加载数据后手动 invalidateLayout()。 iOS9 不需要,iOS11 也不需要。所以,要么他们改变了主意,要么这是一个错误 :)
只需调用 invalidateLayout()
即可避免崩溃,如下所示:
self.collectionView.reloadData()
self.collectionView.collectionViewLayout.invalidateLayout() // Fix iOS10 crash
我在 iOS 10 上遇到了这个错误,但它在 iOS 11 和 iOS 9 上都工作正常。
* 由于未捕获的异常 'NSRangeException' 而终止应用程序,原因:'* -[__NSArrayM objectAtIndex:]:索引 5 超出范围 [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,但仍然崩溃。有点奇怪,以前有人遇到过这个问题吗?
我也遇到过。 Apple 似乎对 iOS10 进行了一些修改,强制在重新加载数据后手动 invalidateLayout()。 iOS9 不需要,iOS11 也不需要。所以,要么他们改变了主意,要么这是一个错误 :)
只需调用 invalidateLayout()
即可避免崩溃,如下所示:
self.collectionView.reloadData()
self.collectionView.collectionViewLayout.invalidateLayout() // Fix iOS10 crash