0

I have multiple buttons, representing data input (scores). When 1 button is selected, change it's background to 1 colour. All other buttons should be set to a different colour, showing which is currently selected (toggled).

I have used the info from this thread to implement an @IBAction function to change the button. I used the Swift v4 reply / solution as the basis, essentially a single function as:

    @IBAction func buttonPressToggle(_ sender: UIButton) {
        sender.isSelected = !sender.isSelected
        if sender.isSelected {
            sender.backgroundColor = UIColor.orange
        } else {
            sender.backgroundColor = UIColor.green
        }
    }

All buttons use the same function, so I can target the button through the sender local variable. I can also use the tag property, but I haven't done anything with this currently.

What is missing with this is to "reset" any other button's state / background colour, as it is no longer selected.

B25Dec
  • 2,301
  • 5
  • 31
  • 54
jingo_man
  • 509
  • 3
  • 13

2 Answers2

0

You could do something like the following:

class ViewController: UIViewController {

    @IBOutlet var collectionOfButtons: Array<UIButton>?
    
    private let selectionColor = UIColor.orange
    private let nonSelectedColor = UIColor.green
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func buttonPressToggle(_ sender: UIButton) {
        guard let buttons = collectionOfButtons else { return }
        
        for btn in buttons {
            if btn.tag == sender.tag {
                btn.backgroundColor = selectionColor
            } else {
                btn.backgroundColor = nonSelectedColor
            }
        }
    }

So basically we store the outlet for each button in an array and if one button got selected, we loop through this array and check, whether the current button (btn) was the selected one and if so, we set it's backgroundColor to a different one.
So for this approach the buttons should been taged.

I have uploaded my sample project: https://github.com/finebel/ToggleButtons

finebel
  • 2,227
  • 1
  • 9
  • 20
0
    @IBAction func buttonPressToggle(_ sender: UIButton) {
        self.buttons.forEach {
            $0.backgroundColor = ($0 == sender) ? UIColor.orange : UIColor.green
        }
    }
Li Jin
  • 1,879
  • 2
  • 16
  • 23