我有一个UITextField作为子视图。
- (void)viewDidLoad {
[super viewDidLoad];
textField = [[UITextField alloc] initWithFrame:CGRectMake(21, 21, 159, 37)];
textField.borderStyle = UITextBorderStyleNone;
textField.font = [UIFont systemFontOfSize:15];
textField.placeholder = @"name";
textField.autocorrectionType = UITextAutocorrectionTypeNo;
textField.keyboardType = UIKeyboardTypeDefault;
textField.returnKeyType = UIReturnKeyDone;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.textColor = [UIColor whiteColor];
textField.keyboardAppearance = UIKeyboardAppearanceDark;
textField.delegate = (id) self;
textField.autocapitalizationType = UITextAutocapitalizationTypeNone;
[textField addTarget:self action:@selector(saveData:) forControlEvents:UIControlEventEditingDidEnd];
[self.view addSubview:textField];
}
-(void)saveData:(id)sender {
NSString *savestring = textField.text;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:savestring forKey:@"savedstring"];
[defaults synchronize];
}
加载数据(viewDidLoad)
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadstring = [defaults objectForKey:@"savedstring"];
[textField setText:loadstring];
现在的问题是它不会保存并加载UITextField的文本。
答案 0 :(得分:0)
首先,您需要在文本字段中输入一些字符串并按回车键,这样它才有机会调用您的" saveData"方法并将值存储在NSUserDefaults中。只需检查所有值。
答案 1 :(得分:0)
我找到了解决方案:
textField.text = [defaults objectForKey:@"savedstring"];
感谢大家的回答
答案 2 :(得分:0)
“addSubview”在此方法写入后加载数据方法...
[self.view addSubview:textField];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *loadstring = [defaults objectForKey:@"savedstring"];
[textField setText:loadstring];