Saving bool to NSUserDefaults and using it in a if statement using Swift

后端 未结 6 1265
遇见更好的自我
遇见更好的自我 2021-02-19 21:44

I am struggling to figure out how to do an if statement with a bool saved to NSUserDefaults using Swift. I believe I know how to save the bool to NSUserDefaults but a confirmati

6条回答
  •  无人及你
    2021-02-19 22:12

    Swift 3

    This is code for the switch, that will save true or false to UserDefaults.

    let defaults = UserDefaults.standard
    @IBOutlet weak var mySwitch: UISwitch!
    
    @IBAction func switchValueChanged(_ sender: Any) {
        self.defaults.set(mySwitch.isOn, forKey: "mySwitch")
    }
    

    Then to show the switch's saved state... on/off:

    override func viewDidLoad() {
        super.viewDidLoad() 
        mySwitch.isOn = self.defaults.bool(forKey: "mySwitch")
    }
    

    So really 1 line to set the switch's state, and 1 line to get the users saved state and set the switch properly!

提交回复
热议问题