"Index Out Of Range" 数据源数组正确时 UICollectionView 出错

"Index Out Of Range" error in UICollectionView when dataSource array is correct

我正在使用 sizeForItemAt indexPath 和 UICollectionView。

当我执行从 collectionView 和 dataSource 数组中删除项目的操作时,我调用 reloadData。但是,在 sizeForItem 中,我得到了 Fatal error: Index out of range.

dataSource 计数正确,反映了变化。例如,从 4 到 3 个项目。 sizeForItem 试图访问的 indexPath 是 0 - 3,第四个索引。

为什么会出现此错误? sizeForItemcellForItemnumberOfItemsInSection 之前运行是否重要?

删除项目并调用 reloadData 后,将调用 sizeForItem。以下是委托和数据源方法:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return array.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionViewCell", for: indexPath)
    cell.updateStyle
    return cell
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let view = array[indexPath.row]
    return view.intrinsicContentSize
}

如果我能澄清,请告诉我。

编辑:这是我从数据源数组中删除项目的地方

func deleteItem() {
    removeItem(item)
    collectionView.reloadData()
}

正如@ozzieozumo 所说,对 sizeForItemAt indexPath 的调用是在 reloadData 之前调用的。

更改数据源数组后,我将 reloadData 调用更改为先到。