1

In SWIFT, I am using a viewcontroller (VC2) to hold a datePicker which I get the date from and pass it back to VC1. VC1 have a button which load VC2 through segue. The problem that when I get the first date and unwindsegue back to VC1 and next I try to tap the button in VC1 again to change the date I find the datePicker date is set to Today and not the last I chosen. How can I keep the first chosen date/time in the datePicker when I next try to change it?

I mean when the datePicker is used in the same VC the date/time chosen the first time will be kept in the datePicker if you decided to change the date again.

Regards, Mohamed

I tried the following: In VC1:

let storyBoard = UIStoryboard(name: "Main", bundle: nil)

var vc = storyBoard.instantiateViewControllerWithIdentifier("datePickerVc1") as! UIViewController

self.presentViewController(vc, animated: true, completion: nil)

In VC2:

@IBAction func exit(sender: AnyObject) {

  self.dismissViewControllerAnimated(true, completion: nil)

}

And still the datePicker returns to its default state i.e., the date will be back to Today's date.

Hvordan har du det
  • 3,605
  • 2
  • 25
  • 48
hamoti71
  • 21
  • 3

3 Answers3

1

Thank you guys for your answers. I found the solution. Put the following code before leaving the modal view VC2:

let currentDate = datePicker.date
    NSUserDefaults.standardUserDefaults().setObject(currentDate, forKey: "Current-Date")

In viewDidLoad in VC2 put the following:

if let date = NSUserDefaults.standardUserDefaults().objectForKey("Current-Date") as? NSDate {
        datePicker.setDate(date, animated: true)

Thanks to David Silverfarmer in this link Save datePicker value using NSUserdefaults(xcode,swift2)

Thanks

Mohamed

Community
  • 1
  • 1
hamoti71
  • 21
  • 3
0

If you create a local variable to keep hold of a reference to VC2 and show it on VC1 rather than using a segue then the state of VC2 will not change back to the default when you show it for a second time. I would suggest using a lazy variable to store it

Swinny89
  • 7,273
  • 3
  • 32
  • 52
0

You can either keep a pointer to the date picker VS as Swinny suggests, or you can give your date picker view controller a startingDate property. If you do that, set startingDate in your VC1 prepareForSegue, and then in your date picker VC's viewWillAppear, install the starting date into the date picker.

Duncan C
  • 128,072
  • 22
  • 173
  • 272
  • I want to add that I am using present modally in segue. I know very easier solutions to utilize the datePicker like from the textField instead of the keyboard however, I liked that to show the datePicker as an alert or actionSheet. I am doing it like this url: http://www.totem.training/swift-ios-tips-tricks-tutorials-blog/ux-chops-dim-the-lights – hamoti71 Apr 04 '16 at 11:40
  • Understood. Both Swinny's and my answers assume that your date picker is in a separate view controller. – Duncan C Apr 04 '16 at 12:09