实现上一页./Next按钮在UITableView使第一响应者在一个不可见的单元格UITextField



在我的应用程序中,我有一个UITabeViewUITextField s在每个单元格内。然而,我有困难实现上一个/下一个按钮,使前一个/下一个UITableViewCell内的文本字段是第一个响应者。

我已经子类化了UITableViewCell类,让它调用delegate的某个方法。/next按钮被按下,并传递单元格本身作为这个方法的参数(所以我可以得到它的索引路径来计算哪个是单元格的索引路径,其文本字段必须是第一响应者)

在委托方法I的实现中:

  • 获取按下按钮的单元格的索引路径
  • 从单元格的索引路径中添加或减去1(取决于按下了哪个按钮)
  • 使用表视图上的-cellForRowAtIndexPath:方法获取textfield必须成为第一响应者的单元格
  • 使文本字段成为第一响应者

问题是-cellForRowAtIndexPath:方法仅在单元格可见时返回该单元格。因此,当单元格不可见时,它将返回nil,上述算法将不起作用,而当单元格在屏幕上时,它将正确工作。

这是我的代码。按钮,前提是MUInfoMateriaTableViewCellUITableViewCell的子类,并且它具有返回其文本字段的textField属性:

- (void)prevButtonPressedInCell:(MUInfoMateriaTableViewCell *)cell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSIndexPath *previousIndexPath = [NSIndexPath indexPathForRow:indexPath.row-1 inSection:indexPath.section];
    MUInfoMateriaTableViewCell *newCell = (MUInfoMateriaTableViewCell *)[self.tableView cellForRowAtIndexPath:previousIndexPath];
    [newCell.textField becomeFirstResponder];
}

是否有任何方法"获得"一个不可见的单元格,以便我可以使其文本字段成为第一响应者?或者你能建议我另一种算法来解决这个问题吗?

你可以通过多步骤来解决这个问题:

  • 跟踪包含所需文本字段的单元格,以使第一响应者
  • 计算要显示的单元格的NSIndexPath并调用[self.tableView scrollToRowAtIndexPath:atScrollPosition:animated:]将其带入视图
  • 实现tableView:willDisplayCell:forRowAtIndexPath:调用becomeFirstResponder对所需的单元格,当它变得可见,它匹配所需的单元格或索引路径

最后一步很重要,因为如果接收器不是任何窗口的子视图,调用becomeFirstResponder不会做任何事情。

通过滚动表格视图使单元格可见,使用scrollToRowAtIndexPath:atScrollPosition:animated:

例如

- (void)prevButtonPressedInCell:(MUInfoMateriaTableViewCell *)cell
{
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSIndexPath *previousIndexPath = [NSIndexPath indexPathForRow:indexPath.row-1 inSection:indexPath.section];
    [self.tableView scrollToRowAtIndexPath:previousIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
    MUInfoMateriaTableViewCell *newCell = (MUInfoMateriaTableViewCell *)[self.tableView cellForRowAtIndexPath:previousIndexPath];
    [newCell.textField becomeFirstResponder];
}

问题是-cellForRowAtIndexPath:方法返回

这是因为当行不可见时单元格不存在。UITableView只保留那些用来绘制表格的单元格。这就是为什么当你滚动表格时,你会得到很多-tableView:cellForRowAtIndexPath:消息——表格要求它的数据源提供它没有的单元格。

如果您想使用当前的方法,您需要滚动表格,以便要编辑的行变得可见,如Gabriele Petronella的回答所示。

最新更新