1

I have 3 buttons. When one is selected, I want the background to be white. I can handle this part. My problem is that when I select one of the unselected buttons, I want the color of the button I selected to revert to the old color. How can I do this?

@IBOutlet weak var xButton: UIButton!

@IBOutlet weak var yButton: UIButton!

@IBOutlet weak var zButton: UIButton!

var button_isActive: Bool = false

    @IBAction func btn_Button(_ sender: UIButton) {
    if button_isActive {
        UIView.animate(withDuration: 0.2) {
            sender.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
            
        }
    } else {
        UIView.animate(withDuration: 0.2) {
            sender.backgroundColor = #colorLiteral(red: 0.1098039216, green: 0.1098039216, blue: 0.1098039216, alpha: 1)
        }
    }
    button_isActive = !button_isActive
}

enter image description here

When I clicked the X button the color of the background changes. When I clicked the Y button the color of the background changes but the background color of the x button remains the same. I want it to return to the old background color

enter image description here

2
  • So should each button has the same color on selection state? Commented Nov 7, 2020 at 10:26
  • all buttons have gray background color. When I selected it turns white. When I clicked Y button I want to deselect other buttons and turn their background gray again Commented Nov 7, 2020 at 10:32

1 Answer 1

1

You could store the outlets inside an array. To do so, watch the following video: https://www.youtube.com/watch?v=bFfPT37Yh8c
After that you will have to create one action for all of your buttons (here it's called buttonPressToggle).

@IBAction func buttonPressToggle(_ sender: UIButton) {
    //buttons -> your outlet collection
    for btn in buttons {
        if btn == sender {
            btn.backgroundColor = .white
        } else {
            btn.backgroundColor = .gray
        }
    }
}

Or even shorter:

@IBAction func buttonPressToggle(_ sender: UIButton) {
    self.buttons.forEach { $0.backgroundColor = ($0 == sender) ? UIColor.white : UIColor.gray }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.