覆盖textFieldShouldEndEditing时按下取消按钮
我有一个详细视图与一些领域,其中一些使用textFieldShouldEndEditing做一些验证。这一切运作良好。但是,如果用户在字段中输入了无效数据,然后按下取消按钮,则验证例程仍会在调用textFieldShouldEndEditing时运行。有没有办法来防止这种情况?换句话说,只要得到一个干净的取消,因为我不在乎该字段包含什么。覆盖textFieldShouldEndEditing时按下取消按钮
取消按钮函数内部 清楚你当前的TextField.text = @ “”;
检查textFieldShouldEndEditing最初
if ([textfield.text isEqualtoEmpty:@""]
{
return Yes;
}
else{
// check your condition here
}
优秀 - 像魅力一样工作。非常感谢! –
Senthikumar的回答工作在特定的情况下,但我不得不在我需要检查该字段也没有空了类似的情况......
所以我使用以下技术:
- 我创建了一个叫做布尔属性 “cancelButtonPressed”
- 在连接到取消按钮的方法中,我设置此BOOL为YES
- 在textViewShouldEndEditing,首先检查该BOOL。如果它不是,我会执行我的控制(例如包括警报视图)。此方法应始终通过呼叫返回YES完成;,这意味着如果该“cancelButtonPressed” BOOL是YES,它应该结束的文本字段编辑(和我的脸,例如不会引发警报)。
此外(这是没有直接联系的问题,但它通常是与“取消”功能),你也可以有一个“保存”按钮,在这种情况下,要防止用户保存,如果你正在编辑一个文本字段和条目不正确。
在这种情况下,我创建一个名为“textFieldInError”另一个BOOL,如果我在 textViewShouldEndEditing控制未能将其设置为YES,并且NO如果我的控制成功(在方法的结束)。 然后,在链接到我的保存按钮的方法中,我检查此BOOL是否。
下面是完整的代码:
@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];
}
我希望可以帮助其他人,因为我有一个大伤脑筋在清洁,简单的解决这个办法。
Fred
谢谢弗雷德,你帮了我,使至少一个人。好的简单解决方案 – MortalMan
请问您可以在这里详细说明您的代码,以便我们明白您的意思! – iDhaval