我正在处理具有多个 UITextField
对象的 View 。我的 View Controller 用作 UITextFieldDelegate
,我已经实现了 (BOOL)textFieldShouldEndEditing:(UITextField *)textField
方法来保存和验证正在显示的记录。
如果用户在编辑项目后单击“完成”按钮并且保存/验证失败,则会显示 UIAlertView
并且用户会停留在 UITextField
验证失败。
我的问题是——当用户点击 UITextField
时,将无法保存/验证到另一个 UITextField
,然后 (BOOL )textFieldShouldEndEditing:(UITextField *)textField
方法被多次调用,多次弹出UIAlertView
为什么 (BOOL)textFieldShouldEndEditing:(UITextField *)textField
在用户单击键盘上的“完成”时调用一次,但在用户单击另一个 UITextField< 时调用多次
?
这是我的代码:
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
NSLog(@"textFieldShouldEndEditing called by textField with text=%@", textField.text);
currentItem.nameOrNumber = nameOrNumber.text;
// Try to save the managed object.
NSError *error = nil;
if (![[currentItem managedObjectContext] save:&error]) {
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Uh Oh!",@"")
message:[error localizedDescription]
delegate:self
cancelButtonTitle:NSLocalizedString(@"OK",@"")
otherButtonTitles:nil];
[errorAlert show];
[errorAlert release];
shouldEnd = NO;
}
return shouldEnd;
}
最佳答案
我认为您的问题出在编辑文本字段并直接点击另一个文本字段时调用文本字段方法的顺序。
如果我没记错的话,应该是这样的(你在A上编辑然后点击B)
textFieldShouldBeginEditing
字段 BtextFieldShouldEndEditing
字段 AtextFieldDidEndEditing
字段 AtextFieldDidBeginEditing
字段 B
所以当你在 textFieldShouldEndEditing
方法中时,文本字段 B 已经成为第一响应者。因此,当您使 UIAlertView 出现时,B 会失去焦点,因此也会调用 textFieldShouldEndEditing
!
当我想在 textField 开始编辑时提升 View 时,这对我来说也是个问题。我找到的解决方案是创建一个 bool 类变量,指示我当前是否正在从一个文本字段切换到另一个文本字段。
我在 textFieldShouldBeginEditing
中将其设置为 TRUE
,在 textFieldDidBeginEditing
中将其设置为 FALSE
。当您在 textFieldShouldEndEditing
中时,如果它设置为 TRUE
,则意味着用户直接点击了另一个文本字段。然后你只需要找到正确的方法来只进行一次测试(也许 shouldEndEditing 应该返回 false 或其他东西)。
关于ios - 多次调用 textFieldShouldEndEditing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3121440/