由于某种原因,我无法将文本字段设置为第一响应者。
我有一个包含两行的 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 returned 1
becomeFirstResponder returned 0
我尝试过的:
- 返回 YES 而不是 NO
- 删除对 canBecomeFirstResponder 的调用(仅用于调试目的)
任何提示表示赞赏!
在按照tmadsen的建议进行操作后,我发现了错误。错误是这一行:
UITableViewCell *cell = [self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:k
它返回一个新单元格,而不是当前屏幕上的单元格。我把它替换为
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:kPasswordRowInde
现在它按预期工作了。
附带说明一下,我发现 0 是 tag 属性的默认值,因此使用它可能不太聪明。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)