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