简体   繁体   中英

use func to alternative either task a or b every time it is called

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM