这是 switft 代码。我想将当前红色的按钮的背景颜色更改为蓝色。然而,它再次被点击,我希望它从蓝色变成红色。我通常会这样做。
var counter = 0
var button = UIButton()
func switch(){
if counter % 2 == 0 {
button.backgroundcolor = .blue
}
else {
button.backgroundcolor = .red }
counter += 1}
我写这个问题是因为尽管我正在做的事情正在发挥作用。我认为必须有一种更有效的方法来编写代码,而不是声明 var 并对其进行潜水。
最佳答案
因为只有两种状态将 counter
声明为 Bool
var backgroundColorIsBlue = false
在 switch
函数中(由于 switch
是保留字而无法编译),只需切换(反转)Bool 并设置背景颜色即可。如果 backgroundColorIsBlue
为 true
,三元运算符使用 ?
之后的值,否则使用 :
之后的值。
@objc func switchAction(_ sender : UIButton) {
backgroundColorIsBlue.toggle()
sender.backgroundColor = backgroundColorIsBlue ? .blue : .red
}
关于swift - 每次调用时使用 func 来替代任务 a 或 b,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59480013/