Removed Selected State on Button While Clicking a Different Button (Swift)

2.6k views Asked by At

I'm trying to figure out the logic in toggling button states in Swift. The concept is very simple:

  • I have three buttons on the screen.
  • When I click one button, it toggles to a 'selected' state
  • When I click a different button, I want it to toggle the currently selected button to a 'non-selected' state and toggle the new button to 'selected'

I have this function I use on TouchUpInside for the buttons on the screen but at the moment it's possible to have them all 'selected' which I don't want:

func highlightTrack(sender:UIButton){
    if(!sender.selected){
        sender.selected = true
        sender.backgroundColor = UIColor.blueColor()
    } else {
        sender.selected = false
    }
}

I come from the world of Javascript so I may just have my logic crossed up but is there a way to detect currently selected buttons on the screen and turn them off or is this closer to a 'radio' button type logic?

My issue is that these buttons are created programmatically depending on certain conditions so technically I'm not supposed to be created IBOutlets on the fly like that correct (IB meaning 'Interface Builder'?)?

Thanks for your help!

2

There are 2 answers

1
nickburdak On
func highlightTrack(sender:UIButton) {
    if sender.isSelected {
        return
    }

    btn1.isSelected = false
    btn2.isSelected = false
    sender.isSelected = true
}
0
Krunal On

Connect following action function with all your three buttons using TouchUpInside control event.

button1.addTarget(self, action: #selector(self.highlightTrack(button:)), for: .touchUpInside)
button2.addTarget(self, action: #selector(self.highlightTrack(button:)), for: .touchUpInside)
button3.addTarget(self, action: #selector(self.highlightTrack(button:)), for: .touchUpInside)

@IBAction func highlightTrack(button: UIButton) {

   if button.isSelected {
     return
   }

   button1.isSelected = false
   button1.backgroundColor = UIColor.white

   button2.isSelected = false
   button2.backgroundColor = UIColor.white

   button3.isSelected = false
   button3.backgroundColor = UIColor.white

   button.isSelected = true
   button.backgroundColor = UIColor.blue

}

Another solution:

@IBAction func highlightTrack(button: UIButton) {

   if button.isSelected {
     return
   }

   updateButtionSelectionState(button: button, isSelected: (button == button1))
   updateButtionSelectionState(button: button, isSelected: (button == button2))
   updateButtionSelectionState(button: button, isSelected: (button == button3))

}


func updateButtionSelectionState(button: UIButton, isSelected: Bool) {
   button.isSelected = isSelected
   button.backgroundColor = isSelected ? UIColor.blue : UIColor.white
}