我有自定义CollectionView
单元格,按下按钮点按我closure
cellForItem
下面是代码
cell.closeImageTappped = { [weak self] cell in
guard let strongSelf = self else {
return
}
if let objectFirst = strongSelf.selectedFiles.first(where: {$0.fileCategory == cell.currentSelectedCellType && $0.fileName == cell.currentObject?.fileName}) {
cell.imgPicture.image = nil
cell.imgPlusPlaceHolder.isHidden = false
objectFirst.removeImageFromDocumentDirectory()
strongSelf.selectedFiles.remove(at: strongSelf.selectedFiles.index(where: {$0.fileName == objectFirst.fileName})!)
strongSelf.arraySource[indexPath.section].rows.remove(at: indexPath.row)
strongSelf.collectionViewSelectFile.performBatchUpdates({
strongSelf.collectionViewSelectFile.deleteItems(at: [indexPath])
}, completion: nil)
}
}
应用程序在某些情况下崩溃,例如我是否过快关闭多个单元格
崩溃
strongSelf.arraySource[indexPath.section].rows.remove(at: indexPath.row)
致命错误:索引超出范围
当我检查行
时▿11个元素 - 0:0 - 1:1 - 2:2 - 3:3 - 4:4 - 5:5 - 6:6 - 7:7 - 8:8 - 9:8 - 10:8
虽然IndexPath是
po indexPath
▿ 2 elements
- 0 : 0
- 1 : 11
如果我像这样获得indexPath,它会显示正确的IndexPath
self?.collectionViewSelectFile.indexPath(for: cell)
▿ Optional<IndexPath>
▿ some : 2 elements
- 0 : 0
- 1 : 9
但为什么IndexPath
与self?.collectionViewSelectFile.indexPath(for: cell)
答案 0 :(得分:1)
indexPath
来自闭包之外,因此在将闭包分配给单元格时捕获其值。我们假设你的阵列中有10个项目,你删除了第9个项目。你的数组现在有9个项目,但显示第10个项目(但现在是第9个项目 - 数组中的索引8)的单元格仍然有9个indexPath.row
,而不是8个,所以你得到一个数组尝试删除最后一行时违反边界。
要避免此问题,您可以在闭包内的集合视图上使用indexPath(for:)
,以确定单元格的当前indexPath
:
cell.closeImageTappped = { [weak self] cell in
guard let strongSelf = self else {
return
}
if let objectFirst = strongSelf.selectedFiles.first(where: {$0.fileCategory == cell.currentSelectedCellType && $0.fileName == cell.currentObject?.fileName}),
let indexPath = collectionView.indexPath(for: cell) {
cell.imgPicture.image = nil
cell.imgPlusPlaceHolder.isHidden = false
objectFirst.removeImageFromDocumentDirectory()
strongSelf.selectedFiles.remove(at: strongSelf.selectedFiles.index(where: {$0.fileName == objectFirst.fileName})!)
strongSelf.arraySource[indexPath.section].rows.remove(at: indexPath.row)
strongSelf.collectionViewSelectFile.performBatchUpdates({
strongSelf.collectionViewSelectFile.deleteItems(at: [indexPath])
}, completion: nil)
}
}