使用UIswitch来设置值我的变量是静态的,因为我在不同的swift文件中使用它们所以当我运行程序并单击注册按钮时它打印nil甚至它打开(按钮保持在关闭应用程序时留下的方式)我必须切换它然后单击注册按钮,它打印可选(true)我能做什么,这样用户不必每次打开应用程序时切换或当应用程序打开时显示但值为零也我只是想要打印真/假(我怎么解开)
class FirstViewController: UIViewController, UITextFieldDelegate {
static var FirstColor: Bool!
@IBAction func home(_ sender: RoundButton) {
}
@IBAction func Registration(_ sender: RoundButton) {
print(FirstViewController.FirstColor)
}
@IBAction func ColorSwitch(_ sender: UISwitch) {
if sender.isOn{
FirstViewController.FirstColor = true
}else{FirstViewController.FirstColor = false }
}
}
如果要保留交换机状态,则需要将其存储在UserDefaults中。不要在FirstViewController中添加静态属性。使用computed属性创建一个单独的类
class Color {
static var firstColor: Bool {
get { return UserDefaults.standard.bool(forKey: "firstColor") }
set { UserDefaults.standard.set(newValue, forKey: "firstColor") }
}
}
在FirstViewController的viewDidLoad中获取最后一个状态并进行更新
override func viewDidLoad() {
super.viewDidLoad()
mySwitch.isOn = Color.firstColor
}
在Switch的操作中更改它
@IBAction func ColorSwitch(_ sender: UISwitch) {
sender.isOn = !sender.isOn
Color.firstColor = sender.isOn
}
您可以尝试直接使用isOn属性的值。这有帮助吗?另外,我建议您为处理程序使用更好的名称。
class FirstViewController: UIViewController, UITextFieldDelegate
{
static var FirstColor: Bool!
@IBAction func registrationTapped(_ sender: RoundButton)
{
print(FirstViewController.FirstColor)
}
@IBAction func colorChanged(_ sender: UISwitch)
{
FirstViewController.FirstColor = sender.isOn
}
}