【问题标题】:becomeFirstResponder on UITextView not workingUITextView 上的 becomeFirstResponder 不起作用
【发布时间】:2009-12-13 12:44:50
【问题描述】:

由于某种原因,我无法将文本字段设置为第一响应者。

我有一个有两行的 UITableView。每行都有一个标签和一个 UITextField。文本字段标记为 kLoginRowIndex = 0 和 kPasswordRowIndex = 1。您可能已经猜到,我使用它来设置登录名和密码。

如果用户在编辑登录文本字段时点击返回按钮,我希望密码文本字段获得焦点。不幸的是,密码文本字段不接受焦点。这是我的代码:

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    NSLog(@"%s:(textField.tag:%d)", __FUNCTION__, textField.tag);
    [textField resignFirstResponder];
    if(textField.tag == kLoginRowIndex) {
        UITableViewCell *cell = [self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:kPasswordRowIndex inSection:0]];
        UITextField *nextTextField = (UITextField *)[cell viewWithTag:kPasswordRowIndex];
        NSLog(@"(nextTextField.tag:%d)", nextTextField.tag);
        NSLog(@"canBecomeFirstResponder returned %d", [nextTextField canBecomeFirstResponder]);
        NSLog(@"becomeFirstResponder returned %d", [nextTextField becomeFirstResponder]);
    } else {
        [self validate:textField];
    }
    return NO;
}

这是日志输出:

-[SettingsViewController textFieldShouldReturn:]:(textField.tag:0)
(nextTextField.tag:1)
canBecomeFirstResponder 返回 1
becomeFirstResponder 返回 0

我尝试了什么:

  • 返回 YES 而不是 NO
  • 删除对 canBecomeFirstResponder 的调用(仅用于调试目的)

感谢任何提示!

【问题讨论】:

    标签: iphone uikit uitextfield


    【解决方案1】:

    在玩了tmadsen的建议后,我发现了错误。错误是这一行:

    UITableViewCell *cell = [self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:k
    

    它返回一个新单元格,而不是当前屏幕上的那个。我把它替换为

    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:kPasswordRowInde
    

    现在它按预期工作了。

    顺便说一句,我发现 0 是 tag 属性的默认值,所以使用它可能不太聪明。

    【讨论】:

      【解决方案2】:

      0 是标签属性的默认值,因此您可能希望使用 0 以外的值,否则您很可能在调用 viewWithTag 时返回超级视图:

      【讨论】:

      • 你是对的。这不是我的代码的问题,但是使用 0 作为标记绝对不是一个好主意。
      【解决方案3】:

      自从我为 iPhone 开发以来已经有一段时间了,我从未使用过您在代码中显示的标签。但是您可以通过创建类的文本字段属性来做您想做的事情。如果你这样做了,假设你将这些属性命名为 loginTextField 和 passwordTextField,那么你可以让下一个 textField 的焦点如下:

      - (BOOL)textFieldShouldReturn:(UITextField *)textField {
          if([self usernameTextField] == textField) {
              return [[self passwordTextField] becomeFirstResponder];
          }
          else {
              // your validating code...
          }
      
          return NO;
      }
      

      但正如我所说,已经有一段时间了,我不知道你所说的这个标签,所以也许这是一些新的最佳实践,但上面的代码应该可以工作

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多