0

I have an array of buttons which will act like a selector menu. I want that when I press one of them, it changes its backgroundColor and all the other buttons go back to their initial color.

This is what I have at the moment

 @IBAction func optionSelected(_ sender: UIButton) {

    for button in selectButtons {
        if button.tag == sender.tag {

        if !button.isSelected {
            button.backgroundColor = palette.importantColorObject()
            button.isSelected = true
        } else {
            button.backgroundColor = palette.clearGrayColorObject()
            button.isSelected = false
        }

        }
    }

But I don't know how to make that only the last selected button have this importantColorObject and I'm also having the problem that when I select the button, not only its background color changes, but it looks also like if text inside was being selected (in blue). How can I solve this?

Thanks in advance

emelagumat
  • 301
  • 2
  • 10
  • 1
    There are plenty of answers [here](https://stackoverflow.com/questions/29117759/how-to-create-radio-buttons-and-checkbox-in-swift-ios) that should get you started. – Don Mar 17 '19 at 19:46

1 Answers1

0

This will solve your only one selection problem, this will make sure that you always have a selected button, unless you to deselect selected one and all your button go to gray or not selected state.

@IBAction func optionSelected(_ sender: UIButton) {

    selectButtons.forEach { (button) in
        button.backgroundColor = palette.clearGrayColorObject()
        button.isSelected = false
    }

    sender.backgroundColor = palette.importantColorObject()
    sender.isSelected = true
}

if you want that functionality too use this one

@IBAction func optionSelected(_ sender: UIButton) {
   if sender.isSelected {
       sender.backgroundColor = palette.clearGrayColorObject()
       sender.isSelected = false
   } else {
       selectButtons.forEach { (button) in
           button.backgroundColor = palette.clearGrayColorObject()
           button.isSelected = false
       }

       sender.backgroundColor = palette.importantColorObject()
       sender.isSelected = true
   }
}

Hope this will help.

Arashk
  • 617
  • 5
  • 16