验证UITextField输入并显示错误
问题描述:
验证UITextField中的用户输入并显示错误的最佳做法是什么?我尝试在textFieldShouldReturn
和textFieldShouldEndEditing
内执行检查,并在userever输入无效内容时弹出错误框。验证UITextField输入并显示错误
但是,在测试期间,从textFieldShouldEndEditing
弹出多次调用。我的简单测试是在TextFieldA中输入无效文本并直接导航到TextFieldB。我观察到3个错误弹出窗口,所有产生的textFieldShouldReturn
答
这可能是通过展示警报,编辑栏失去焦点,并由此发出另一个textFieldShouldReturn或textFieldShouldEndEditing。
尝试推迟警报,通过将代码,以显示警报到一个单独的方法,和从textFieldShouldEndEditing调用该方法使用[自performSelector:@selector(yourAlertMethod)withObject:无afterDelay:0]
其实,我发现前段时间我有类似的问题。诀窍是确保文本字段在显示警报的持续时间内不再有焦点。
这里是我的解决方案:
// declare this in your interface as part of your ivars:
UITextField *currTextField;
// here comes the code to check for bad input and show an alert:
#pragma mark -
#pragma mark UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
if ([self acceptsEntry:textField.text]) { // this checks if the text is valid
// We're done here
return YES;
} else {
// Setting the delegate to nil will prevent the textField to listen for Return key events.
textField.delegate = nil;
// Removing the observer will prevent the user from typing into the textfield using an external keyboard
[textField resignFirstResponder];
currTextField = textField;
UIAlertView *av = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"invalidEntry", @"")
message:NSLocalizedString(@"invalidEntryMessage", @"")
delegate:self
cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
[av show];
[av release];
}
return NO;
}
#pragma mark -
#pragma mark UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
// gets called when the user dismisses the alert view
currTextField.text = @""; // erase bad entry
currTextField.delegate = self; // We want to listen for return events again
[currTextField becomeFirstResponder];
currTextField = nil;
}
是您的UITextField委托多个领域的代表,或只是一个? – Ricky 2011-03-24 06:11:53