我有一个详情视图,其中包含许多字段,其中一些使用textFieldShouldEndEditing来进行一些验证。这一切都很顺利。然而,如果用户在字段中输入无效数据,然后按下取消按钮,验证程序仍然运行,因为textFieldShouldEndEditing被调用。有没有办法防止这种情况发生?换句话说,只是得到一个干净的取消,因为我不关心该字段包含什么。
我有一个详情视图,其中包含许多字段,其中一些使用textFieldShouldEndEditing来进行一些验证。这一切都很顺利。然而,如果用户在字段中输入无效数据,然后按下取消按钮,验证程序仍然运行,因为textFieldShouldEndEditing被调用。有没有办法防止这种情况发生?换句话说,只是得到一个干净的取消,因为我不关心该字段包含什么。
在取消按钮函数内部
清除您当前的textfield文本。textfield.text=@"";
最初检查textFieldShouldEndEditing
if ([textfield.text isEqualtoEmpty:@""]
{
return Yes;
}
else{
// check your condition here
}
这里是完整的代码:
@property (nonatomic) BOOL cancelButtonPressed;
@property (nonatomic) BOOL textFieldInError;
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
// If the user pressed Cancel, then return without checking the content of the textfield
if (!self.cancelButtonPressed) {
// Do your controls here
if (check fails) {
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"Incorrect entry"
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[av show];
// Prevent from saving
self.textFieldInError = YES;
return NO;
}
}
// Allow saving
self.textFieldInError = NO;
return YES;
}
- (void)saveButtonPressed;
{
// Resign first responder, which removes the decimal keypad
[self.view endEditing:YES];
// The current edited textField must not be in error
if (!self.textFieldInError) {
// Do what you have to do when saving
}
}
- (void)cancel;
{
self.cancelButtonPressed = YES;
[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}