crash - 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,但仍然崩溃。有点奇怪,有人遇到过这个问题吗?
解决方案
它也发生在我身上。似乎 Apple 在 iOS10 上引入了一些修改,强制在重新加载数据后手动 invalidateLayout()。这在 iOS9 上不需要,在 iOS11 上也不需要。所以,要么他们改变了主意,要么这是一个错误:)
只需调用invalidateLayout()
以避免崩溃,如下所示:
self.collectionView.reloadData()
self.collectionView.collectionViewLayout.invalidateLayout() // Fix iOS10 crash
推荐阅读
- php - 直接在占位符后使用光标进行表单输入。引导程序 4
- reactjs - 在 React 中,当在 url 中手动更改路由参数时,全局状态会不同步
- python - 在 Python 中查找独眼巨人数
- angular - 如果模块未导入路由模块,则 Angular 应用程序无法工作
- latex - 通过标签离线编译 Overleaf 项目参考图
- node.js - .then 不要等到承诺完成
- javascript - 如何从存储在 Firebase 中的数组中检索对象的 id?
- python - 在询问他们的情况后,我如何让我的助手在 python 代码中对“你好吗”的预设响应做出响应
- mongodb - 具有管道的反应式 MongoDB 聚合框架查找阶段
- javascript - 刷新页面时,我的 .filter 反应丢失