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

问题描述 投票:0回答:1

我有一个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]的第一项,则下一个(第二个)项目变为1-st但它的按钮索引仍为[0,1]。

我做错了什么以及为什么按钮索引没有重新排列?

swift uicollectionview uicollectionviewcell
1个回答
2
投票

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

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

@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])
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.