Caspert
Caspert

Reputation: 4363

How to toggle background between two buttons in Swift?

I created an app with two buttons. What I want is when the left button is clicked, it will change it's background color. If the right button is clicked, change that background color.

Above concept is working with the following code for both buttons:

 @IBAction func pressedButton(_ sender: UIButton) {

        sender.backgroundColor = (sender.backgroundColor == Constants.BOOL_BUTTON.enabled) ? Constants.BOOL_BUTTON.disabled : Constants.BOOL_BUTTON.enabled

    }

Both buttons are linked to this function. The only thing what is not working, is that when the left button for example had the enabled color and the user then clicks on the right button to change his choice, the left button will not be resetting to it's disabled color. How can I achieve this with above function?

Upvotes: 1

Views: 1269

Answers (1)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52133

The problem with your code is when right or left button is pressed, it doesn't know about the state of the other one. What you can do is:

@IBAction func pressedButton(_ sender: UIButton) {
  if sender.backgroundColor == Constants.BOOL_BUTTON.enabled {
    return
  }
  sender.backgroundColor = Constants.BOOL_BUTTON.enabled

  switch sender {
  case self.leftButton:
    self.rightButton.backgroundColor = Constants.BOOL_BUTTON.disabled

  case self.rightButton:
    self.leftButton.backgroundColor = Constants.BOOL_BUTTON.disabled

  default:
    return
  }
} 

Upvotes: 1

Related Questions