When I tap on button it will trigger multiple times.
CollectionViewCell file code
class PhotoCell: UICollectionViewCell {
@IBOutlet weak var deleteButton: UIButton!
}
ViewController – cellforItemAt method implementation
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCell", for: indexPath) as? PhotoCell else { return UICollectionViewCell() }
let action = UIAction { _ in
print("Delete button tapped!!!", indexPath.row)
}
cell.deleteButton.addAction(action, for: .touchUpInside)
return cell
}
If I configure UIButton addTarget then it work fine but I am not sure why it’s not working with addAction.
2
Answers
One possible solution is to override
prepareForReuse()
inPhotoCell
, asJohann
mentioned.We can remove all events from the button there!
Add action in
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
like normally we do.The actions get triggered multiple times because some instances of
PhotoCell
are reused by theUICollectionView
. This means that thedeleteButton
of thePhotoCell
returned bydequeueReusableCell()
may already have actions added to it and will eventually possess multiple actions for the same events.One possible solution is to override
prepareForReuse()
inPhotoCell
and remove the actions there.When using the above code
addAction
needs to be called oncell
instead ofcell.deleteButton
in the functionfunc collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
: