【问题标题】:"Index Out Of Range" error in UICollectionView when dataSource array is correct数据源数组正确时 UICollectionView 中的“索引超出范围”错误
【发布时间】:2017-12-05 15:16:20
【问题描述】:

我将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
}

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

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

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

【问题讨论】:

  • 显示您执行删除和重新加载的部分。
  • @ozzieozumo 已添加
  • 你在哪里调用你的集合视图的 deleteItems 方法?基本上,我怀疑在您删除后,您的数据源的项目比您的集合视图少。你必须让它们保持同步。
  • @ozzieozumo 我打电话给deleteItems 以响应按钮按下。 reloadData 不是让它们保持同步吗?我正在改变 dataSource 数组,然后调用 reloadData
  • 您对 reloadData 的看法是正确的,但对 sizeForItem 的调用似乎是在您调用 reloadData 之前发生的。在您的问题中,您说“ sizeForItem 在 etc 之前运行是否重要”。如果您的集合和数据源在 sizeForItem 运行时不同步,这很重要。

标签: ios swift xcode uicollectionview uicollectionviewlayout


【解决方案1】:

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

改变 dataSource 数组后,我将 reloadData 调用更改为先调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多