I'm trying to change the backgroundColor
for a button on tap. When the button is tapped, it should change the backgroundColor
. But my problem is that I need two taps for this event. And I don't understand why.
My code:
for (index, cue) in cuestionesCC.enumerated(){
let buttonYes = UIButton()
buttonYes.backgroundColor = .green
buttonYes.titleEdgeInsets = UIEdgeInsets(top: -10, left: -10, bottom: -10, right: -10) // Add padding around text
buttonYes.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
buttonYes.tag = 1
buttonYes.setTitle("Yes", for: .normal)
buttonYes.addTarget(self, action: #selector(buttonActionYesNo), for: .touchUpInside)
let buttonNo = UIButton()
buttonNo.backgroundColor = .red
buttonNo.titleEdgeInsets = UIEdgeInsets(top: -10, left: -10, bottom: -10, right: -10) // Add padding around text
buttonNo.contentEdgeInsets = UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5)
buttonNo.tag = 2
buttonNo.setTitle("No", for: .normal)
buttonNo.addTarget(self, action: #selector(buttonActionYesNo), for: .touchUpInside)
stackViewH.addArrangedSubview(buttonYes)
stackViewH.addArrangedSubview(buttonNo)
}
@objc func buttonActionYesNo(sender: UIButton!) {
print (sender.tag)
sender.backgroundColor = .gray
}
When I tap the button once, it prints the tag. But I need another tap additional for change the backgroundColor
of the button. I don't understand that logic.