[英]use func to alternative either task a or b every time it is called
This is in switft code.这是在 switft 代码中。 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.
我认为必须有一种更有效的方式来编写代码,而不是声明一个 var 并将其潜水。
As there are only two states declare counter
as Bool因为只有两个状态将
counter
声明为 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.在
switch
函数中——它不能编译,因为switch
是一个保留字——只需切换(反转)Bool 并设置背景颜色。 The ternary operator uses the value after the ?
三元运算符使用
?
之后的值?
if backgroundColorIsBlue
is true
otherwise the value after the :
.如果
backgroundColorIsBlue
为true
则为:
之后的值。
@objc func switchAction(_ sender : UIButton) {
backgroundColorIsBlue.toggle()
sender.backgroundColor = backgroundColorIsBlue ? .blue : .red
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.