2009-12-13 35 views
3

由于某些原因,我无法将textfield作为第一响应者。UITextView无法正常工作的第一个响应者

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

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

- (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 returned 1 
becomeFirstResponder returned 0

我试了一下:

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

任何提示感谢!

回答

10

玩了tmadsen的建议后,我发现了错误。错误是这条线:

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

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

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

现在它按预期工作。

在附注中,我发现0是标签属性的默认值,因此使用它可能不那么聪明。

0

自从我为iPhone开发之后,我从未使用过在代码中显示的标签。但是你可以通过创建你的类的textfields属性来做你想做的事。如果你这样做,让我们说你的名字的那些属性loginTextField和passwordTextField,那么你就可以让如下的下一个文本框聚焦:

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

    return NO; 
} 

但正如我所说,它已经有一段时间,我不知道这个标签的东西,你谈论,所以也许这是一些新的最佳做法,但上面的代码应该是工作

+0

谢谢!虽然不是我正在寻找的东西,但你的回答帮助我指出了正确的方向。 标签可用于识别视图对象。 http://developer.apple.com/iPhone/library/documentation/UIKit/Reference/UIView_Class/UIView/UIView.html#//apple_ref/doc/uid/TP40006816-CH3-SW25 – 2009-12-13 14:52:35

3

0是标签属性,所以你可能需要使用除0以外的默认值,否则,你将最有可能返回上海华当你调用viewWithTag:

+0

你说得对。这不是我的代码的问题,但使用0作为标记绝对不是一个好主意。 – 2009-12-13 21:38:41

相关问题