Swift 我的UIswitch值为零,即使它处于打开状态,我也必须先关闭Switch,然后再打开它才能设置值

Swift 我的UIswitch值为零,即使它处于打开状态,我也必须先关闭Switch,然后再打开它才能设置值,swift,uiswitch,Swift,Uiswitch,使用UIswitch设置值 我的变量是静态的,因为我在不同的swift文件中使用它们 所以,当我运行程序并点击注册按钮时,它打印为零 即使打开了(按钮仍保持关闭应用程序时的状态) 我必须切换它,然后单击“注册”按钮,以打印可选内容(true) 我该怎么做才能让用户不必在每次打开应用程序或应用程序打开时显示时切换,但值为零 此外,我只希望它打印真/假(如何展开) 如果要保持交换机状态,需要将其存储在UserDefaults中。不要在FirstViewController中添加静态属性。使用comp

使用UIswitch设置值 我的变量是静态的,因为我在不同的swift文件中使用它们 所以,当我运行程序并点击注册按钮时,它打印为零 即使打开了(按钮仍保持关闭应用程序时的状态) 我必须切换它,然后单击“注册”按钮,以打印可选内容(true) 我该怎么做才能让用户不必在每次打开应用程序或应用程序打开时显示时切换,但值为零 此外,我只希望它打印真/假(如何展开)


如果要保持交换机状态,需要将其存储在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
}
在开关的动作中改变它

@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
    }
}

请考虑在你所写的文章中使用句号仍然是苹果违约的原因吗?此外,每当我运行应用程序时,即使我在停止应用程序时关闭了开关,也会打开开关。关闭应用程序时,您必须保持该状态。看看UserDefaults类(特别是set和bool func).@kishan你在关闭开关时没有将开关的状态存储在任何地方app@kishan在FirstViewController的viewDidLoad中,您需要获得持久值,并根据该值更改开关。是的,我认为这应该起作用。我不知道在关闭应用程序时设置状态的方法。ThxName按钮加载为on,我一注册就不触摸按钮按钮值打印为零,所以既然按钮加载为on,你们知道每次打开应用程序时如何加载为off,我只需设置静态变量FirstColor:Bool!伪造
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
    }
}