Shift72
Shift72

Reputation: 448

Swift: How to keep ViewControllers in exact same condition?

I have two view controllers and in ViewController 1 I have a date picker and a text field. I have another ViewController that displays what you have entered in that date picker and text field. I have a ¨change¨ button that returns you to that first view controller and a ¨doen¨button that show view controller 2. As of now the text in the textfield and the date that the user has selected, is gone every time you close the app or click the ¨change button(Go back to View controller 1).

How can i keep the text in the text field, and the selected date in the date picker.

I want the user to be able to change the information that has already been added.

Please add code.

https://i.sstatic.net/SIvK3.jpg (Picture of the main storyboard)

Upvotes: 0

Views: 98

Answers (2)

Pranav Wadhwa
Pranav Wadhwa

Reputation: 7746

What you could try doing is saving the data before exiting the view controller. In the viewWillDisappear method, you could add

 NSUserDefaults.standardUserDefaults().setObject(textField.text, forKey: "userText")
 NSUserDefaults.standardUserDefaults().setObject(datePicker.date, forKey: "userDate")

Later, when you reopen the same view controller, in the viewDidLoad method, you could add

if  NSUserDefaults.standardUserDefaults().objectForKey("userText") != nil {
    textField.text = NSUserDefaults.standardUserDefaults().objectForKey("userText") as! String
}

if  NSUserDefaults.standardUserDefaults().objectForKey("userDate") != nil {
    datePicker.setDate(NSUserDefaults.standardUserDefaults().objectForKey("userDate") as! NSDate, animated: true)
}

I do not use date pickers very frequently, but I believe this is the correct code. Otherwise, it would be very similar. Hope this helps.

Upvotes: 0

o15a3d4l11s2
o15a3d4l11s2

Reputation: 4059

The way you are showing the ViewControllers is not optimal. In the best case, when you show something new (ViewController2), then dismiss it, it should lead you back to the previous screen (ViewController1). It should not instantiate a new instance of ViewController1, as the segues in you case are doing.

Please note that depending on how you present the second view the solution would be different.

In case your segue from the first controller to the second is a "Show" segue, you can just add the following to your "Change" button:

@IBAction func changeButtonPressed(sender: AnyObject) {
  self.dismissViewControllerAnimated(true, completion: nil)
}

In case you have a navigation controller (I do not see such on the screenshot), then you can use

@IBAction func changeButtonPressed(sender: AnyObject) {
  self.navigationController.popViewControllerAnimated(true)
}

Upvotes: 1

Related Questions