Xcode: Why doesn't my app save the UITextField?
I have an app where I switch to a view with a TableView using presentModalViewController. The View with the TableView is however not at UITable开发者_如何学编程ViewController but a regular UIViewController. I have written UITextFields into the UITableViewCells. I use this action to save what the user inputs:
- (IBAction)saveTextField:(id)sender {
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:TextField.text forKey:@"keyTextField"];
[userDefaults synchronize]; }
I call this method with this code:
[TextField addTarget:self action:@selector(hideKeyboard:) forControlEvents:UIControlEventEditingDidEndOnExit];
When I dismiss the ViewController using dismissModalViewController and then when I presents it again I call the NSUserDefaults in the ViewDidLoad with this code:
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
TextField.text = [userDefaults objectForKey:@"keyTextField"];
Problem is that it doesn't work. And I can't figure out the problem. Any help would be appreciated.
Thanks in advance :)
The target
has to be the same as your method, meaning that if you have - (void)saveTextField:(id)sender
then you code to add the target need to be
[TextField addTarget:self action:@selector(saveTextField:) forControlEvents:UIControlEventEditingDidEndOnExit];
Check usin NSLog
if your action is being run.
Instead of setting a target, can't you do that saving with the textFieldDidEndEditing: delegate method?
use this code in view did load NSUserDefaults *user=[NSUserDefaults standardUserDefaults]; TextField.text=[user stringForKey:@"keyTextField"];
To begin with: thanks to all of you for your effort and time :)
Turns out the problem wasn't with the code that saves and loads it. The problem was that I only created one UITextfield which I then put into every UITableViewCell and that was the problem. So I created individual UITextFields for every UITableViewCells and that fixed the problem :)
精彩评论