按下取消按钮时覆盖textFieldShouldEndEditing

时间:2012-06-20 13:01:44

标签: ios iphone ipad uitextfield

我有一个包含许多字段的详细信息视图,其中一些字段使用textFieldShouldEndEditing进行一些验证。这一切都运作良好。但是,如果用户在字段中输入无效数据然后按下取消按钮,则验证例程仍会在调用textFieldShouldEndEditing时运行。有办法防止这种情况吗?换句话说,只是得到一个干净的取消,因为我不在乎该字段包含什么。

2 个答案:

答案 0 :(得分:1)

取消按钮功能 清除你当前的textfield.text = @“”;

最初检查textFieldShouldEndEditing

if  ([textfield.text isEqualtoEmpty:@""] 
{
return Yes;
}
else{

// check your condition here

}

答案 1 :(得分:1)

Senthikumar的答案适用于那个特例,但我有一个类似的案例,我需要检查该字段是否也是空的......

因此我使用了以下技术:

  1. 我创建了一个名为“cancelButtonPressed”的BOOL属性
  2. 在链接到取消按钮的方法中,我将此BOOL设置为YES
  3. textViewShouldEndEditing 中,我首先检查此BOOL。如果是NO,我会进行控制(例如包括警报视图)。这个方法总是应该通过调用返回YES; 来完成,这意味着如果这个“cancelButtonPressed”BOOL为YES,它应该结束文本字段编辑(例如,不要在我脸上发出警报)。
  4. 另外(这与问题没有直接关联,但它通常带有“取消”功能),你可能还有一个“保存”按钮,在这种情况下你想要如果您正在编辑textField并且条目不正确,则阻止用户保存 在这种情况下,我创建另一个名为“textFieldInError”的BOOL,如果我的控件在,则将其设置为YES textViewShouldEndEditing失败,如果我的控件成功(在方法结束时)为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];
    }
    

    我希望这可以帮助其他人,因为我以一种干净,直接的方式解决了这个问题。

    佛瑞德

相关问题