【问题标题】:IndexPath for next/previous UITextField within UITableViewUITableView 中下一个/上一个 UITextField 的 IndexPath
【发布时间】: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];
            });
        }];

【问题讨论】:

    标签: ios objective-c uitableview uitextfield


    【解决方案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 类。一旦你得到实例,打破循环滚动到你刚刚得到的那个单元格(或者根据你的喜好取出索引路径)
    猜你喜欢
    • 1970-01-01
    • 2011-07-08
    • 1970-01-01
    • 2011-02-19
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多