0

我有自定义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)

4

1 回答 1

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)
        }

    }
于 2017-11-08T09:20:40.533 回答