【问题标题】:Button was enabled only for two textfields in cells both had entered text in there仅对单元格中的两个文本字段启用了按钮,两个文本字段都在其中输入了文本
【发布时间】:2013-07-03 11:58:35
【问题描述】:

我有两个UITextfield,两个cells,一个section,一个grouped UITableView,分别称为emailFieldpasswordField,他们将tag设置为0和1。我有一个@ 987654328@ 在navigationBar 的右边缘调用了loginButton。我希望在此视图进入屏幕时禁用该按钮,并希望在 textFields 都在其中输入文本时启用该按钮,否则该按钮被禁用。

这是创建按钮的代码。

_loginButton = [[UIBarButtonItem alloc] initWithTitle:@"Login"
                                                   style:UIBarButtonItemStyleDone
                                                   target:self
                                                   action:@selector(logging)];

    _loginButton.enabled = NO;
    self.navigationItem.rightBarButtonItem = _loginButton;

UITextFieldtextFieldDidBegingEditing:方法中,我尝试实现这个功能。但它不起作用或工作不正确,这很奇怪。注意:textFields 添加为cellsubview 而不是cell contentView's subview

#pragma mark - UITextfield Delegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField == self.emailField)
    {
        UITableViewCell *currentCell = (UITableViewCell *)textField.superview;
        NSIndexPath *currentIndexPath = [self.tableView indexPathForCell:currentCell];
        NSIndexPath *nextIndexPath = [NSIndexPath indexPathForRow:currentIndexPath.row+1 inSection:0];
        UITableViewCell *nextCell = [self.tableView cellForRowAtIndexPath:nextIndexPath];
        self.passwordField = (UITextField *)[nextCell viewWithTag:1];
        if ([(UITextField *)[currentCell viewWithTag:0] text].length != 0 && [(UITextField *)[nextCell viewWithTag:1] text].length != 0)
        {
            self.loginButton.enabled = YES;
        }
        else
        {
            self.loginButton.enabled = NO;
        }
    }
}

我也尝试在按钮选择器方法中实现这个功能,但根本不起作用。

- (IBAction)logging
{
    if (self.emailField.text.length > 0 && self.passwordField.text.length > 0)
    {
        self.loginButton.enabled = YES;
    }
    else
    {
        self.loginButton.enabled = NO;
    }
}

这是怎么回事?

【问题讨论】:

  • 你试过调试它吗?设置断点,看看你是否得到了正确的文本字段。
  • 您的代码是否到达 self.loginButton.enabled = YES 语句?
  • 使用 viewWithTag:0 时必须非常小心,因为 0 是视图标签的默认值。任何没有专门设置标签的视图都将返回 0。这可能不是您所期望的行为。

标签: ios cocoa-touch uitextfield uibarbuttonitem


【解决方案1】:

您是否将 textfields 委托属性设置为 self? 这段代码还有其他一些问题,但我会先检查一下

【讨论】:

  • 您可能希望将此添加为对问题的评论而不是答案。看起来更合适。
  • 谢谢,我在创建文本字段时设置了委托。
  • @MySpecialPurpose erian 在评论问题方面没有足够的声誉
  • 是的,这就是我没有将其添加为评论的原因
猜你喜欢
  • 2013-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-17
  • 2017-12-27
  • 2015-07-08
  • 2013-02-11
  • 1970-01-01
相关资源
最近更新 更多