我正在使用这个SO答案来给我的UITableViewCell
添加UITextField
。然而,我现在不知道应该如何让用户通过使用下一个按钮聚焦到下一个项目。有什么提示吗?
[[UIView viewWithTag:nextTag] becomeFirstResponder]
将焦点更改到下一个文本字段。这对我很有效,但需要根据您的需求进行微调:
#pragma mark - UITextField Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
HRCFormCell * currentCell = (HRCFormCell *) textField.superview.superview;
NSIndexPath * currentIndexPath = [self.tableview indexPathForCell:currentCell];
if (currentIndexPath.row != [self.questionsArray count] - 1) {
NSIndexPath * nextIndexPath = [NSIndexPath indexPathForRow:currentIndexPath.row + 1 inSection:0];
HRCFormCell * nextCell = (HRCFormCell *) [self.tableview cellForRowAtIndexPath:nextIndexPath];
[self.tableview scrollToRowAtIndexPath:nextIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
[nextCell.textField becomeFirstResponder];
}
return YES;
}
UITableViewScrollPositionTop
。 - Jason McCreary除了Anh提到使用标签值来查找下一个字段并使其成为第一响应者之外...
如果你在UITableView中,你还需要记住下一个UITextField可能不在屏幕上,甚至可能不在视图中,因为它可能在屏幕底部以下。在使其成为第一响应者之前,你可能需要滚动新行到视图中。在之前的一个应用程序中,我处理这个问题的方法是使标签成为一个可以用来表示NSIndexPath的值,这样我就可以弄清楚它位于哪一行。然后,你可以使用以下代码将该行滚动到视图中:
[tableView scrollToRowAtIndexPath:newIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
然而,这会创建一个竞争条件,即当您调用becomeFirstResponder时,单元格尚未可见,因此我会延迟becomeFirstResponder直到它可见为止。我会在我的类中设置一个值作为属性,例如字段的行号,该字段应成为第一响应者,然后在要显示该单元格的cellForRowAtIndexPath或willDisplayCell: forRowAtIndexPath中,当我将要显示该单元格时,我会在textfield上调用becomeFirstResponder,因为此时它保证已经存在。
你想要做什么?
NSArray *arrayCells = [self.aTableView visibleCells];
UITableViewCell * currentCell = (UITableViewCell *) textField.superview.superview;
NSIndexPath * currentIndexPath = [self.aTableView indexPathForCell:currentCell];
if ((currentIndexPath.row != [arrayCells count] - 1) && (currentIndexPath.row < [arrayCells count]-1)) {
NSIndexPath * nextIndexPath = [NSIndexPath indexPathForRow:currentIndexPath.row + 1 inSection:0];
UITableViewCell * nextCell = (UITableViewCell *) [self.aTableView cellForRowAtIndexPath:nextIndexPath];
[self.aTableView scrollToRowAtIndexPath:nextIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
for (id object in nextCell.contentView.subviews) {
if ([object isKindOfClass:[UITextField class]]) {
UITextField *tf = object;
[tf becomeFirstResponder];
}
}