How to save text temporary in textfield?

2019-08-29 07:42发布

问题:

I have a little problem, when I have text put in a UITextfield in view controller A and I go to an other view controller and then i go back to view controller A the text in the textfield had disappear.

Is there a way to save the text temporary in the textfield? So the text won't disappear when you go to an other view controller.

回答1:

when you navigate the page at that time save the data in NSUserDefaults .

NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject:textfield.text forKey:@"textfield value"];
    [defaults synchronize];

and re assign the textfield value in viewWillAppear method.

NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
   textfield.text= [defaults  valueForKey:@"textfield value"];

or

other wise take an global string and assign the string value to textFiled and Vice Versa.



回答2:

Use UINavigationController. You can then add a screen to navigation stack using pushViewController and remove a screen from stack using popViewController. Your contents in textfield will be preserved when you come back.



回答3:

You can use Global variable and store text in that global variable.

To achieve this you can user .pch file of AppDelegate file to manage Global variable.

Or you can user NSUserDefaults.

Hope this will help you.

All the best !!!



回答4:

Yes there are number of methods. If you want the text to be visible only when the app is running then save the text in a global NSString and add it to the UITextfield in your viewWillAppear method.

Your you can set a property as global too, where you can add declare the string in your AppDelgate or in a global singleton class.

If you want to save the variable/string then use NSSUserDefaults