在UserDefaults中保存UISwitch状态

时间:2018-05-15 16:22:38

标签: ios swift nsuserdefaults uiswitch

我想用UserDefaults保存UISwitch标签的​​状态。我的代码如下所示:

func viewDidAppear() {
    mySwitch.setOn(userDefaults.standard.bool(forKey: "mySwitchValue"), animated: true)
}

func viewWillDesappear() {
    UserDefaults.standard.set(mySwitch.isOn, forKey: "mySwitchValue")
}

但是在应用程序中,当我离开切换视图并返回时,UISwitch在我转动时并不是。

2 个答案:

答案 0 :(得分:1)

可能之前,rmaddy指出的是问题。在那种情况下,请去拼写。

否则,当视图消失时,设置开关状态的值可能不是一个明智的选择。当应用程序进入后台时,其他进程会同时执行,并且可能在应用程序关闭之前设置默认值。

我通常会在调用这些函数时设置这些值,即在switch操作中。一旦用户更改了切换状态,请将其保存在defaults中,当您在viewDidAppear时检索切换状态时,它会正常工作。

import UIKit

class ViewController: UIViewController {

    let userDefaults = UserDefaults.standard

    @IBOutlet weak var mySwitch: UISwitch!

    @IBAction func switchAction(_ sender: UISwitch) {
        userDefaults.set(sender.isOn, forKey: "mySwitchValue")
    }

    override func viewDidAppear(_ animated: Bool) {
        mySwitch.isOn = userDefaults.bool(forKey: "mySwitchValue")
    }
}

演示如下:

enter image description here

答案 1 :(得分:0)

这不是原始查询的答案,而是评论中另一个查询的答案。 问题:如果首次启动应用程序,如何将UISwitch的默认状态设置为on? 虽然理想情况下,它应该被问为另一个问题,因为它是增量的,代码如下:

import UIKit

class ViewController: UIViewController {

    let userDefaults = UserDefaults.standard

    var firstTimeAppLaunch: Bool {
        get {
            // Will return false when the key is not set.
            return userDefaults.bool(forKey: "firstTimeAppLaunch")
        }
        set {}
    }

    @IBOutlet weak var mySwitch: UISwitch!

    @IBAction func switchAction(_ sender: UISwitch) {
        userDefaults.set(sender.isOn, forKey: "mySwitchValue")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        if !firstTimeAppLaunch {
            // This will only be trigger first time the application is launched.
            userDefaults.set(true, forKey: "firstTimeAppLaunch")
            userDefaults.set(true, forKey: "mySwitchValue")
        }

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func viewDidAppear(_ animated: Bool) {
        mySwitch.isOn = userDefaults.bool(forKey: "mySwitchValue")
    }

}

请注意,您可以在AppDelegate的功能中执行此操作:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Could add the above code within this as well. Upto you. 
        return true
    }