Saving and retrieving a bool with UserDefaults

前端 未结 4 1376
醉酒成梦
醉酒成梦 2021-01-13 01:33

I\'m trying to save a bool value to UserDefaults from a UISwitch, and retrieve it in another view. However, I\'ve tried following multiple tutorials and stack answe

4条回答
  •  北海茫月
    2021-01-13 02:19

    Do it like this.

    In your first view controller.

    • create an IBoutlet connection to your UISwitch

    • And then the action for your UISwitch. so in the end, your first view controller should look like this.

    import UIKit

    class FirstViewController: UIViewController {
    
    
        @IBOutlet weak var myswitch: UISwitch! // Outlet connection to your UISwitch (just control+ drag  it to your controller)
    
    
    
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
    
        }
    
        @IBAction func myswitchAction(_ sender: Any) { // Action for your UISwitch
    
            var myswitctBool : Bool = false // create a local variable that holds your bool value. assume that in the beginning your switch is offed and the boolean value is `false`
    
            if myswitch.isOn == true { // when user turn it on then set the value to `true`
                myswitctBool = true
            }
            else { // else set the value to false
                myswitctBool = false
            }
    
    
            // finally set the value to user default like this
            UserDefaults.standard.set(myswitctBool, forKey: "mySwitch")
            //UserDefaults.standard.synchronize() - this is not necessary with iOS 8 and later.
    
    
        }
    
    }
    

    End of the first view controller

    Now in your second view controller

    • you can get the value of userdefault, which you set in first view controller. I put it in the viewdidload method to show you how it works.

    import UIKit

    class SecondViewController: UIViewController {
    
            override func viewDidLoad() {
                super.viewDidLoad()
    
    
                let myswitchBoolValuefromFirstVc : Bool = UserDefaults.standard.bool(forKey: "mySwitch")// this is how you retrieve the bool value
    
    
                // to see the value, just print those with conditions. you can use those for your things.
                if myswitchBoolValuefromFirstVc == true {
                    print("true")
                }
                else {
                    print("false")
                }
    
    
            }
    
            override func didReceiveMemoryWarning() {
                super.didReceiveMemoryWarning()
    
            }
    
    
    
    
        }
    

    Hope this will help to you. good luck

提交回复
热议问题