When I move from one view controller to another, the switch on the first controller resets itself and does not retain its state. How can I make it save its state when come
just after code connect UISwitch to IBoutlet.
class ViewController: UIViewController {
@IBOutlet weak var switchButton: UISwitch!
@objc func switchStateDidChange(_ sender:UISwitch!)
{
if (sender?.isOn == true){
print("on")
}
else {
print("off")
}
UserDefaults.standard.set(sender.isOn, forKey: "switchState")
UserDefaults.standard.synchronize()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(false)
switchButton?.isOn = UserDefaults.standard.bool(forKey: "switchState")
switchButton?.addTarget(self, action: #selector(switchStateDidChange(_:)), for: .touchUpInside)
}
}
Since you're syncing the on/off state of the switch you could on viewWillAppear:
or viewDidAppear:
set the state of the switch to the value stored in NSUserDefaults
Something along the lines of
override func viewWillAppear(animated: Bool) {
self.switchButton.on = NSUserDefaults.standardUserDefaults().boolForKey(switchKey)
}
Xcode 8.3 • Swift 3.1
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var switchButton: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
switchButton.isOn = UserDefaults.standard.bool(forKey: "switchState")
}
@IBAction func saveSwitchPressed(_ sender: UISwitch) {
UserDefaults.standard.set(sender.isOn, forKey: "switchState")
}
}