简体   繁体   中英

UIViewController & UITableViewController - Settings Page

I've made a little app on the UIViewController and I want it to have a settings page.

I made a button on it which leads to a UITableView Controller, so far all I have on it is a toggle for Vibrate but when I turn the switch off, go to main, and return back the switch is reset to original position ('on').

How can I make it so the state stays and where do I define the action for the toggle?

You should at start, load the UI with the settings current values.

In the viewWillAppear or even in viewDidLoad , you can just set the options, it will make the view shows the data as is set.

I make a simple project to demonstrate how to save the switch state. Here's the sample code and you can download the whole project here: https://drive.google.com/file/d/0B2_OK50NaRBpVVE4ZzhORUJJaG8/view?usp=sharing

class ViewController: UIViewController {

    @IBOutlet weak var mySwitch: UISwitch!
    @IBOutlet weak var stateLabel: UILabel!

    let defaults = NSUserDefaults.standardUserDefaults()
    let savedKey = "switch_state"

    override func viewDidLoad() {
        super.viewDidLoad()

        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Clear", style: .Plain, target: self, action: "clearSettings")
        mySwitch.addTarget(self, action: "toggleSwitch", forControlEvents: .ValueChanged)

        // Retrieve data from NSUserDefaults & update switch state and label
        let switchState = defaults.boolForKey(savedKey)
        mySwitch.setOn(switchState, animated: true)
        self.stateLabel.text = "Current state: \(mySwitch.on)"
   }

   func toggleSwitch() {
       // Each time we toogle switch, save switch state
        defaults.setBool(mySwitch.on, forKey: savedKey)
        defaults.synchronize()

        // Update label
        self.stateLabel.text = "Current state: \(mySwitch.on)"
    } 

    func clearSettings() {
        // Remove saved switch state
        defaults.removeObjectForKey(savedKey)
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM