Reputation: 1175
I have a collectionView. Every cell contains button actionButton
to remove them. Button have method removeItem
to remove them thru attached target. I have an array datas
contains items for collection.
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)
}
I have a method to delete item from collection view.
@objc func removeItem(sender: UIButton) {
let indexPath = IndexPath.init(item: sender.tag, section: 0)
self.datas.remove(at: indexPath.item)
collectionView?.deleteItems(at: [indexPath])
}
But after deletion item from collection cells button index not reloaded. For example if I remove 1-st item with index [0, 0] next(second) item became 1-st but it's button index still [0, 1].
What i'm doing wrong and why button index don't rearranges?
Upvotes: 0
Views: 799
Reputation: 318944
Never use tags to track the index path of a cell (in a collection view or a table view). As you've seen, it fails when you can insert, remove, or reorder cells.
The proper solution is to get the index path of the cell based on the location of the button in the collection view.
@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])
}
}
}
Upvotes: 2