Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
672 views
in Technique[技术] by (71.8m points)

ios - How do i keep UISwitch state when changing ViewControllers?

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 back to it after viewing other controllers? And how do I make it save its state after closing the app. I have looked at the various stackOverflow questions and responses and the apple documentation, but nothing seems to work.

Here is my class for the View Controller that has the switch.

class Days: UIViewController {
    @IBOutlet weak var switchButton: UISwitch!
    var switchState = true
    let switchKey = "switchState"
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    @IBAction func saveSwitchPressed(sender:AnyObject) {
        if self.switchButton.on {
            self.switchState = true
            NSUserDefaults.standardUserDefaults().setBool(self.switchState, forKey: switchKey)
            NSUserDefaults.standardUserDefaults().synchronize()
            println(NSUserDefaults.standardUserDefaults().boolForKey(switchKey))
        } else {
            self.switchState = false
            NSUserDefaults.standardUserDefaults().setBool(self.switchState, forKey: switchKey)
            NSUserDefaults.standardUserDefaults().synchronize()
            println(NSUserDefaults.standardUserDefaults().boolForKey(switchKey))
        }
    }
}

I'm a beginner to Swift and generally Xcode. Thank you in advance for your time and help :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...