How do i keep UISwitch state when changing ViewControllers?

前端 未结 3 1188
予麋鹿
予麋鹿 2020-12-01 20:22

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

相关标签:
3条回答
  • 2020-12-01 21:02

    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)
        }
    }
    
    0 讨论(0)
  • 2020-12-01 21:03

    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)
    }
    
    0 讨论(0)
  • 2020-12-01 21:09

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

    enter image description here

    0 讨论(0)
提交回复
热议问题