UITableView 中下一个/上一个 UITextField 的 IndexPath

Posted

技术标签:

【中文标题】UITableView 中下一个/上一个 UITextField 的 IndexPath【英文标题】:IndexPath for next/previous UITextField within UITableView 【发布时间】:2016-08-25 17:59:27 【问题描述】:

我搜索了堆栈溢出 (Getting row of UITableView cell on button press) 并找到了许多人们声称可以工作的解决方案,但我还没有找到完美的解决方案。我正在尝试使用 CGPoint 在我的 UITableView 中获取下一个/上一个 UITextField 的 indexPath,以便我可以滚动到它并使其成为第一响应者。大多数情况下它是正确的,但是如果我的文本字段是另一部分 UITableView 中的前一个字段,我会得到错误的结果。

代码如下(注意:nextTxtField 是 UIView):

CGPoint point = [nextTxtField convertPoint:CGPointZero toView:tableView];        
NSIndexPath *indexPath = [tableView indexPathForRowAtPoint:point];

[UIView animateWithDuration:0.03 delay:0.0 options:0 animations:^
            [tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
         completion:^(BOOL finished) 
            dispatch_async(dispatch_get_main_queue(), ^(void)
                [nextTxtField becomeFirstResponder];
            );
        ];

【问题讨论】:

【参考方案1】:

你可以通过调用 UITableView 的 row/item 获取 indexPath :

[NSIndexPath indexPathForRow:row inSection:section];  
[NSIndexPath indexPathWithIndex:index];  
[NSIndexPath indexPathForItem:item inSection:section];

获得 indexPath 后,您可以通过以下方式获得 UITableViewCell:

[_tableView cellForRowAtIndexPath:indexpath];

它返回一个 UITableViewCell。将其类型转换为您的单元格类(请务必确定)。

然后你可以抓住 nextTxtField 为:

[((YourCellClass *) cell).nextTxtField becomeFirstResponder]  

在 UITableView 滚动到那个 indexPath 之后。

【讨论】:

如果我只获得表格视图和 uitextfield,我需要获取 indexPath。这将不起作用,特别是如果 UITableViewCell 不在视图中, cellForRowAtIndexPath 将由于单元重用而返回 nil。 如何给定一个 uitextfield 实例,该实例包含在 uitableviewcell 中,具有重用标识符。你如何抓住 uitextfield ?? 对不起,我不做单元重用。我分配单元格是因为我必须这样做,我的桌子不会那么大。所以我引用了数组中的控件。 对于文本字段,我需要使用 convertpoint 函数找出索引路径。 如果你有 UITextField 的所有实例,你已经在 Cell 中添加了 subView,我建议你在 Hierarchy(调用 superview)中找到 UITableViewCell 类。一旦你得到实例,打破循环滚动到你刚刚得到的那个单元格(或者根据你的喜好取出索引路径)

以上是关于UITableView 中下一个/上一个 UITextField 的 IndexPath的主要内容,如果未能解决你的问题,请参考以下文章

将 UITextField 添加到 UITableViewCell

在 iPhone 设备中下载文件

如何在GWT中下载文档时在新选项卡上显示消息

如何在 iOS 7 中下载文件之前查找文件的大小?

UITextField 在 iOS 7.1 上没有响应

CSS中下一个元素的选择器的语法是啥?