cmszr
cmszr

Reputation: 59

Change button background color when selected SWIFT

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

Upvotes: 1

Views: 3862

Answers (1)

finebel
finebel

Reputation: 2355

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 }
}

Upvotes: 1

Related Questions