删除单元格后 collectionViewCell 中的按钮索引错误

Wrong index in button inside collectionViewCell after deletion cell

我有一个 collectionView。每个单元格都包含用于删除它们的按钮 actionButton。按钮有方法 removeItem 可以通过附加目标删除它们。我有一个数组 datas 包含要收集的项目。

override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
        super.collectionView(collectionView, willDisplay: cell, forItemAt: indexPath)
        guard let cell = cell as? ViewCell else { return }
        let index = indexPath.row % datas.count
        let item = datas[index]
        cell.item = item
        cell.actionButton.tag = indexPath.item
        cell.actionButton.addTarget(self, action: #selector(removeItem), for: .touchUpInside)
    }

我有一个方法可以从集合视图中删除项目。

@objc func removeItem(sender: UIButton) {
    let indexPath = IndexPath.init(item: sender.tag, section: 0)
    self.datas.remove(at: indexPath.item)
    collectionView?.deleteItems(at: [indexPath])
}

但是从集合单元格按钮索引中删除项目后未重新加载。例如,如果我删除索引为 [0, 0] 的第一个项目,下一个(第二个)项目变为第一个,但它的按钮索引仍然为 [0, 1].

我哪里做错了,为什么按钮索引没有重新排列?

切勿使用标签来跟踪单元格的索引路径(在集合视图或 table 视图中)。如您所见,当您可以插入、删除或重新排序单元格时它会失败。

正确的解决方案是根据集合视图中按钮的位置获取单元格的索引路径。

@objc func removeItem(sender: UIButton) {
    if let collectionView = collectionView {
        let point = sender.convert(.zero, to: collectionView)
        if let indexPath = collectionView.indexPathForItem(at: point) {
            self.datas.remove(at: indexPath.item)
            collectionView.deleteItems(at: [indexPath])
        }
    }
}