Button add target function not called in CollectionView cell

250 Views Asked by At

I have a collection view where each of the cells has a delete button. I added the following code to cellForItemAt indexPath function.

let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellTwo", for: indexPath) as! CustomCellTwo

cell.deleteButton.layer.setValue(indexPath.row, forKey: "index")

cell.deleteButton.addTarget(self, action: #selector(deleteCell), for: .touchUpInside)

Initially it looked as if it was working great. However, I found out that the add target function does not get called at the first tap if I scroll back and forth and then tap the delete button. If I tap again, it works as expected. Only the first tap does not work.

I have been trying to find a reason and a solution for several hours... Please help provide any ideas and advice.

1

There are 1 best solutions below

1
nadein On

Try to move buttons handling into CustomCellTwo implementation. Handle button event touchUpInside with @IBAction func. Now you can debug it with breakpoint set in this function's body. Also add closure type variable to your CustomCellTwo to pass deleteCell calls into it. So it could also be checked with breakpoint. Example:

class CustomCellTwo: UICollectionViewCell {
    var onDelete: (() -> Void)?
    @IBAction func onDeleteButtonTouch(_ sender: Any) {
        onDelete?()
    }
}


// in your UICollectionViewDataSource

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellTwo", for: indexPath) as! CustomCellTwo
    cell.onDelete = {
        self.deleteCell(indexPath)
    }
}