问题描述
由于某种原因,我无法使文本字段成为第一响应者.
For some reason, I'm having trouble with making a textfield the first responder.
我有两行的UITableView.每行都有一个标签和一个UITextField.这些文本字段被标记为kLoginRowIndex = 0和kPasswordRowIndex =1.您可能已经猜到了,我用它来设置登录名和密码.
I have a UITableView with two rows. Each row has a label and a UITextField. The textfields are tagged kLoginRowIndex = 0 and kPasswordRowIndex = 1. As you might have guessed, I use this for setting login and password.
如果用户在编辑登录文本字段时点击返回按钮,我希望密码文本字段成为焦点.不幸的是,密码文本字段不接受焦点.这是我的代码:
If the user taps on the return button when editing the login textfield, I want the password textfield to get the focus. Unfortunately, the password textfield doesn't accept the focus. Here is my code:
- (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
我尝试过的事情:
- 返回是"而不是否"
- 删除对canBecomeFirstResponder的调用(仅用于调试目的)
任何提示都值得赞赏!
推荐答案
在听完tmadsen的建议后,我发现了错误.错误是这一行:
After playing with the suggestion of tmadsen, I found the error. The mistake is this line:
UITableViewCell *cell = [self tableView:self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:k
它返回一个新的单元格,而不是当前屏幕上的单元格.我将其替换为
It returns a new cell, not the one currently on the screen. I replaced it with
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:kPasswordRowInde
现在它可以正常工作了.
and now it works as expected.
另一方面,我发现0是tag属性的默认值,因此使用它可能不太聪明.
On a side note, I found out that 0 is the default value for the tag property, so it's probably not so clever to use it.
这篇关于在UITextView上成为FirstResponder无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!