UICollectionView scrollToItemAtIndexPath崩溃ios 10

时间:2018-06-13 08:24:21

标签: 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,但仍然崩溃了。有点奇怪,以前有没有人遇到过这个问题?

1 个答案:

答案 0 :(得分:2)

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

只需致电invalidateLayout()以避免崩溃,例如:

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