Engineeroholic Engineeroholic - 4 months ago 7
iOS Question

How to keep text fields values after returning from modal in swift?

I wonder how can I keep textfields input data when app do segue to a modal and return to the same page?

Scenario: I have a registration page with text fields and buttons, one of the buttons segue to a view controller that is represented as modal. Inside the modal there is a tableview, and when user click on the cell it returns data, and send user back to the registration page, but The fields get empty.

What is the best way to do it?
the only solution I have in mind is to use NSDefaults, not sure if its a good approach.

Clarification:

I did the modal in storyboard, by adding a normal viewController.
Then I connected a segue between the Button and the new viewController, and selected present modally.

I specified a class for the modal "ModalVC", where it has tableview datasource and delegate functions.

then I created another segue between table cell (the one inside ModalVC) to the registration page to send the data back.

thanks

Answer

Using NSUserDefaults would work in this situation. You would have to do several things:

  1. Instantiate a NSUserDefaults instance
  2. When you first open your registration page, for each text field title, check if a string is stored in the defaults for that title (using defaults.valueForKey("key"))
  3. If it is nil, then store the values inside each field by using defaults.setValue(value, forKey: "field name") inside the prepareForSegue function (in other words, right before the modal view appears)
  4. If it is not nil, then load the values stored for each field inside defaults
  5. After the registration is complete, reset the defaults by setting them to nil

Hope this helps :)