Save last datePicker selection

徘徊边缘 提交于 2020-01-15 03:39:28

问题


I have a project with an UIDatePicker.

I want that if I change my UIDatePicker value, for example at 9:23, when I restart my app value is still 9:23 and not the default value. How can I do that?

Here is my code:

@IBOutlet var myDatePicker: UIDatePicker!
var datePicker = /* Get Your Date Picker from somewhere */

// Store value using User Defaults
let currentDate = datePicker.date
NSUserDefaults.standardUserDefaults().setObject(currentDate, forKey: "Current-Date")

// Retrieve Value using User Defaults
if let date = NSUserDefaults.standardUserDefaults().objectForKey("Current- Date") as? NSDate {
   datePicker.setDate(date, animated: true)
}

I tried with standard userDefaults method but not worked.


回答1:


Hi I prepared for you some snipped code:

     import UIKit

        class ViewController: UIViewController {

// I have declared const key property to avoid mistakes (typo)
            let dateKey = "Current-Date"

            @IBOutlet weak var datePicker: UIDatePicker!
            override func viewDidLoad() {
                super.viewDidLoad()
            }

            override func viewDidAppear(animated: Bool) {
                super.viewDidAppear(animated)

    // This line load previous state when view controller did appear
                loadDate(true)
            }

            @IBAction func savePickerData(sender: AnyObject) {
                // When user taps into 'savePickerData' button picker state is saved
                saveDate()
            }

            func saveDate() {
                NSUserDefaults.standardUserDefaults().setObject(datePicker.date, forKey:dateKey)
            }

            func loadDate(animation: Bool) {
                guard let loadedDate = NSUserDefaults.standardUserDefaults().objectForKey(dateKey) as? NSDate else { return }

                datePicker.setDate(loadedDate, animated: animation)
            }

        }

Should works fine :)




回答2:


Your key is not the same "Current-Date" != "Current- Date". That is why it is not working :

    NSUserDefaults.standardUserDefaults().setObject(currentDate, forKey: "Current-Date")
...
    if let date = NSUserDefaults.standardUserDefaults().objectForKey("Current- Date") as? NSDate {

Use a constant to avoid this error:

let keyData = "Current-Date"
    NSUserDefaults.standardUserDefaults().setObject(currentDate, forKey: keyData)
...
    if let date = NSUserDefaults.standardUserDefaults().objectForKey(keyData) as? NSDate {


来源:https://stackoverflow.com/questions/34277619/save-last-datepicker-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!