This is in switft code. I would like to change the background color a button that is currently red to blue. However it tapped again I would like it to change from blue to red. How I normally would do this would be.
var counter = 0
var button = UIButton()
func switch(){
if counter % 2 == 0 {
button.backgroundcolor = .blue
}
else {
button.backgroundcolor = .red }
counter += 1}
I am writing this question because although what I am doing is working. I am thinking there has to be a more efficient way to write code instead of declaring a var and diving it.
As there are only two states declare counter
as Bool
var backgroundColorIsBlue = false
In the switch
function – which doesn't compile because switch
is a reserved word – just toggle (invert) the Bool and set the background color. The ternary operator uses the value after the ?
if backgroundColorIsBlue
is true
otherwise the value after the :
.
@objc func switchAction(_ sender : UIButton) {
backgroundColorIsBlue.toggle()
sender.backgroundColor = backgroundColorIsBlue ? .blue : .red
}