user6868161 user6868161 - 1 year ago 82
iOS Question

How to change Color of button2 in swift when button1 is clicked?

All I want to do is change the

of fiveMinButton and tenMinButton when fiveMinButton is clicked. Why doesn't this code work?
will not work either.

@IBOutlet weak var fiveMinButton: UIButton!

override func viewDidLoad() {

fiveMinButton.addTarget(self, action: Selector(("action:")), for: UIControlEvents.touchUpInside)

func action(sender: UIButton){

if sender === fiveMinButton {

fiveMinButton.backgroundColor = UIColor.gray
tenMinButton.backgroundColor = UIColor.lightgray



Answer Source

There is 2 problems with your code.

  1. The syntax of selectoris wrong
  2. You have added action of your button inside the viewDidLoad that will also wrong, so write that method outside the viewDidLoad as class method.

For first one change selector like this.

fiveMinButton.addTarget(self, action: #selector(action(sender:)), for: UIControlEvents.touchUpInside)

For second problem just write action out side the viewDidLoad.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download