【发布时间】: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,第四个索引。
为什么会出现此错误? sizeForItem 在 cellForItem 或 numberOfItemsInSection 之前运行是否重要?
删除项目并调用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