我有一个modalviewcontroller,上面有两个按钮:取消和保存。有一个可编辑的UITextField。 每当我点击保存按钮我都会保存它但文本没有保存,因为当我点击按钮打开modalviewcontroller时,文本消失。不知道我的代码有什么问题。 这是我的代码:
- (void)viewWillAppear:(BOOL)animated {
self.cancel = self.navigationItem.leftBarButtonItem;
self.save = self.navigationItem.rightBarButtonItem;
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStylePlain target:self action:@selector(cancelAction)];
self.navigationItem.leftBarButtonItem = cancelButton;
[cancelButton release];
UIBarButtonItem *saveButton = [[UIBarButtonItem alloc] initWithTitle:@"Save" style:UIBarButtonItemStylePlain target:self action:@selector(saveAction)];
self.navigationItem.rightBarButtonItem = saveButton;
[saveButton release];
[super viewWillAppear:animated];
}
-(IBAction) cancelAction{
[[self parentViewController] dismissModalViewControllerAnimated:YES];
}
-(IBAction) saveAction{
NSString *text = [textFieldBeingEdited text];
[textFieldBeingEdited setText:text];
[self setDescription:text];
[[self parentViewController] dismissModalViewControllerAnimated:YES];
}
我不确定是否必须使用以下代码将文本保存在textfield中:
- (void)textFieldDidEndEditing:(UITextField *)textField
{
[self dismissModalViewControllerAnimated:YES];
}
答案 0 :(得分:0)
我在您的代码中没有看到您在视图出现时在UITextField
中设置文本的任何位置。您可以在viewWillAppear
方法中添加一些代码,以便在视图显示时设置文本,例如:
[textField setText:[self description]];
(看起来您将NSString
存储在描述变量中。)
此外,如果这是某种可被视为用户默认值的字符串,则可以将字符串存储在那里。我以前用过这个,它很好地填充了我的UITextField
。
代码示例:
-(void)viewDidLoad
{
stringValue = [[NSUserDefaults standardUserDefaults] stringForKey:@"string"];
[textField setText:stringValue];
}
-(IBAction)saveAction
{
stringValue = [textField text];
[[NSUserDefaults standardUserDefaults] setObject:stringValue forKey:@"string"];
}