Disable addTarget event in a UICollectionViewCell programmatically

52 Views Asked by At

I have implemented a function buttonClicked that executes when a UICollectionViewCell is clicked but I want to disable it once a boolean variable is declared as "false"

class CustomCollectionViewCell: UICollectionViewCell {

    let actButton = UIButton()
    var isButtonEnabled = true
    override init(frame: CGRect) {
        
        super.init(frame: frame)
    
        contentView.addSubview(actButton)

      //... some other constraints
            actButton.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
        if isButtonEnabled == false  {
            actButton.removeTarget(self, action:#selector(self.buttonClicked), for: .allEvents)
                                   }
    }
    
    let playerImageX = UIImage(named: PlayerX.mark)
    let playerImageO = UIImage(named: PlayerO.mark)
    
    
    @objc func buttonClicked() {
        if !isButtonEnabled{
            return
        }
        if let collectionView = superview as? UICollectionView,
            let indexPath = collectionView.indexPath(for: self) {
            actButton.tag = indexPath.row
            if PlayerX.turn == true {
                actButton.setImage(playerImageX, for: .normal)
                PlayerX.move.append(actButton.tag) // Store the move in PlayerX's moves array
                toggleTurn(&PlayerX, &PlayerO)
            } else {
                actButton.setImage(playerImageO, for: .normal)
                PlayerO.move.append(actButton.tag) // Store the move in PlayerO's moves array
                toggleTurn(&PlayerO, &PlayerX)
            }

            if didPlayerWin(PlayerX) {
                isButtonEnabled = false
                print("Player X has won!")
                
            } else if didPlayerWin(PlayerO) {
                isButtonEnabled = false
                print("Player O has won!")
            }

            print("Button Clicked \(actButton.tag), PlayerX moves: \(PlayerX.move), PlayerO moves: \(PlayerO.move)")
        }
    }



    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

I tried to disable the function direclty by adding a conditional at the begginin of the code

 if !isButtonEnabled{
            return
        }

but it still response tot he click after it is set to false so I tried to call removeTarget inside the constraints settings like so

if isButtonEnabled == false  {
            actButton.removeTarget(self, action:#selector(self.buttonClicked), for: .allEvents)
        }

but it does not work either. Still keeps responding to the click event.

is there another method to remove addTarget()?

0

There are 0 best solutions below