0

我在一个分组的 UITableView 中有 3 个 UITextFields,我试图找出正确的逻辑,以便在没有任何 UITextFields 为空时启用我的“保存”UIBarButtonItem。

我目前正在使用- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)stringUITextField 委托方法逐字符检测字段的更改,但它提供的结果不一致。

有任何想法吗?

编辑:这是我现在使用的代码。如您所见,我已将文本字段放入数组中,以便遍历它们。就像现在一样,在我在第三个字段中输入第二个字符之前,保存按钮不会启用。它还交替启用/禁用作为字段中的一个一个删除字符。

NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

    BOOL allValid;

    if (newString.length)
    {
        // Cycle through array checking for completeness
        for (int i = 0; i < [textFieldArray count]; i++)
        {
            if ([[[textFieldArray objectAtIndex:i] text] length] > 0)
            {
                allValid = YES;
                NSLog(@"TextField #%i Validates.", i);
            }
            else
            {
                allValid = NO;
                NSLog(@"TextField #%i Does Not Validate.", i);
            }
        }
    }
    else
    {
        NSLog(@"Invalid");
        allValid = NO;
    }

    if (allValid)
        [saveButton setEnabled:YES];
    else
        [saveButton setEnabled:NO];

    return YES;
4

2 回答 2

0

您究竟是如何使用该方法的?这是我的做法:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
  NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
  if (newString.length) {
    //If all the others are also non-empty, enable your button
  }
  return YES;
}

但在用户按下回车键后启用按钮可能更有意义,这更容易处理。只需在文本字段上使用 didEndEditingOnExit 或 didEndEditing 事件并检查它们是否为非空。

于 2010-04-14T22:19:20.387 回答
0

好的,这就是我最终做到的方式。

我创建- (IBAction)validateFields:(id)sender并将其连接到 UITextField 上的 Editing Changed 插座。它看起来像这样。

- (IBAction)validateFields:(id)sender
{
    BOOL valid = YES;

    // On every press we're going to run through all the fields and get their length values. If any of them equal nil we will set our bool to NO.
    for (int i = 0; i < [textFieldArray count]; i++)
    {
        if (![[[textFieldArray objectAtIndex:i] text] length])
            valid = NO;
    }

    [saveButton setEnabled:valid];
}

我已经给了它一个相当不错的选择,并且无法在任何空文本字段组合上启用保存按钮,所以我要说这是要走的路。

于 2010-04-15T01:12:46.020 回答