我是 Swift 的新手,正在处理我的第一个项目(我有一些 Javascript 和 Web 开发经验)。我遇到了麻烦(持续 4 个小时尝试不同的解决方案)。
我有一个应用程序,当按下 UIButton
时,它会将一个值记录到 FireBase (ON)。当它被第二次推送时,它会记录 (OFF) 到数据库。
当我制作按钮时,更改 view.backgroundColor
并将 if else 绑定(bind)到它工作的颜色。
但我终其一生都无法弄清楚如何根据按钮的状态构建我的 if else。我现在最终尝试更改按钮本身的颜色并将 if else 与之相关联。我知道这是一种非常困惑的不当方式。
import UIKit
import Firebase
import FirebaseDatabase
class ViewController: UIViewController {
@IBAction func OnOffButton(_ sender: UITapGestureRecognizer){
if button.backgroundColor == UIColor.white {
OnOff(state:"ON")
OnOffButton.backgroundColor = UIColor.blue
} else{
OnOff(state:"OFF")
OnOffButton.backgroundColor = UIColor.white
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
OnOff(state: "Off")
OnOffButton.backgroundColor = UIColor.white
}
最佳答案
UIButton
继承自具有 isSelected
属性的 UIControl
。使用它来跟踪状态。通常你会使用 button.isSelected == true
来对应你的开启状态,而 false
是你的关闭状态。
要切换状态,您可以使用 button.isSelected = !button.isSelected
。
对于您的具体示例:
// User pressed the button, so toggle the state:
button.isSelected = !button.isSelected
// Now do something with the new state
if button.isSelected {
// button is on, so ...
} else {
// button is off, so...
}
关于ios - Swift 3 - 基于按钮状态的 If else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42103738/