I'm learning how to use buttons in Swift and I'm changing the color of several of them separately when they are pressed. The problem is that when I press the second button the first one also changes color, and I find it somewhat strange since in theory they are two different functions and one should not affect the other. Anyone know what might be happening?
//
// ViewController.swift
// EjemploProyecto
//
// Created by Mario Miranda on 17/4/22.
//
import UIKit
class ViewController: UIViewController {
//Outlets
@IBOutlet weak var myButton: UIButton!
@IBOutlet weak var button2: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
//Buttons
myButton.backgroundColor = .green
button2.backgroundColor = .blue
}
@IBAction func buttonAction(_ sender: Any) {
if myButton.backgroundColor == .green
{
myButton.backgroundColor = .blue
} else
{
myButton.backgroundColor = .green
}
}
@IBAction func buttonAction2(_ sender: Any) {
if button2.backgroundColor == .blue
{
button2.backgroundColor = .gray
} else
{
button2.backgroundColor = .blue
}
}
}
If you are using Storyboards go to your corresponding UI and with right click on the UI Component you can check the connections with your ViewController, in your case, eliminate the ones that do not correspond.
Or delete all of them and then set them back using the Wizard . (For me it is the most effective and clean way to do it).
Top right of Storyboard
One last tip: set the type corresponding to the UIObjects you use, in this case
UIButton
instead ofAny
.