我想创建一个UIView,当用户完成编辑时,有多个UITextField验证每个UITextField。视图控制器是每个UITextField的委托。当用户更改其中一个UITextFields中的值并触摸键盘上的“done”或触摸视图中的另一个文本字段时,我保存并验证更改。这里的想法是给用户提供即时反馈,如果输入了无效的属性值,则不允许他/她继续进行。
我已阅读Apple的支持文档中的Text and Web Programming Guide,其中建议我将保存/验证逻辑放在textFieldShouldEndEditing:
中:
验证输入字符串的最佳委托方法是textFieldShouldEndEditing:用于文本字段,textViewShouldEndEditing:用于文本视图。在文本字段或文本视图重新调出第一响应者状态之前调用这些方法。返回NO可防止发生这种情况,因此文本对象仍然是编辑的焦点。如果输入的字符串无效,您还应显示警告以通知用户错误。
为了测试这一点,我创建了一个带有一个UIView和两个UITextField的简单项目。根据文档,我在这个测试项目中所做的只是显示一个UIAlertView并返回NO。这是方法:
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
// return YES to allow editing to stop and to resign first responder status. NO to disallow the editing session to end
NSLog(@"In function: textFieldShouldEndEditing:(UITextField *)textField (tag=%i)", textField.tag);
[self logFirstResponder];
// PRETEND THAT THERE IS AN ISSUE THAT FAILS VALIDATION AND DISPLAY
// A UIALERTVIEW.
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Uh Oh!",@"")
message:@"This is a test error"
delegate:self
cancelButtonTitle:NSLocalizedString(@"OK",@"")
otherButtonTitles:nil];
[errorAlert show];
[errorAlert release];
NSLog(@"Displaying Error UIAlertView!!!");
// SINCE THE VALIDATION FAILED, RETURN NO TO HOLD THE USER IN THE
// UITEXTFIELD.
return NO;
}
问题在于:如果用户从一个UITextField点击另一个,则此方法称为 3次,因此UIAlertView显示为 3次。这是我测试的控制台日志:
-- Field One tag = 100, Field Two tag = 200 --
2010-07-02 09:52:57.971 test project[22866:207] In function: textFieldShouldBeginEditing:(UITextField *)textField (tag=100)
2010-07-02 09:52:57.977 test project[22866:207] In function: textFieldDidBeginEditing:(UITextField *)textField (tag=100)
2010-07-02 09:52:57.977 test project[22866:207] Field One is the First Responder.
-- now i'm going to click from Field One into Field Two --
2010-07-02 09:53:18.771 test project[22866:207] In function: textFieldShouldBeginEditing:(UITextField *)textField (tag=200)
2010-07-02 09:53:18.772 test project[22866:207] Field One is the First Responder.
2010-07-02 09:53:18.774 test project[22866:207] In function: textFieldShouldEndEditing:(UITextField *)textField (tag=100)
2010-07-02 09:53:18.774 test project[22866:207] Field One is the First Responder.
2010-07-02 09:53:18.778 test project[22866:207] Displaying Error UIAlertView!!!
2010-07-02 09:53:18.780 test project[22866:207] In function: textFieldShouldBeginEditing:(UITextField *)textField (tag=200)
2010-07-02 09:53:18.781 test project[22866:207] Field One is the First Responder.
2010-07-02 09:53:18.781 test project[22866:207] In function: textFieldShouldEndEditing:(UITextField *)textField (tag=100)
2010-07-02 09:53:18.782 test project[22866:207] Field One is the First Responder.
2010-07-02 09:53:18.783 test project[22866:207] Displaying Error UIAlertView!!!
那是什么交易?似乎我遗漏了一些东西......你如何验证UITextField并正确显示错误?
答案 0 :(得分:8)