如何将 UITableViewCell 滚动到特定位置?

Posted

技术标签:

【中文标题】如何将 UITableViewCell 滚动到特定位置?【英文标题】:How to scroll UITableViewCell to specific position? 【发布时间】:2014-02-15 20:36:10 【问题描述】:

我有一个UITableView,每个UITableViewCell 都有一个UITextField。 When a UITextField is selected I animate the UITableView onto the screen then I change the UITableView size so that the user can see the UITableViewCell that the UITextField is in.

目前一切正常,UITableViewCell 显示在最底部,问题是当用户按下回车键时,我尝试将下一个 UITableViewCell UITextField 设置为第一响应者,然后将其滚动到视图中。 ...但是问题是下一个字段尚未加载,因此我无法访问此字段。

我想知道是否有一种方法可以初始滚动屏幕下半部分的第一个选定的 UITableViewCell / UITextField 2 or 3 up from the bottom so when enter is hit there is no worry about the nextUITextFieldnot being loaded.... currently I have tried writing an off set but it dosnt work if I select aUITextField ......这就是代码的样子。

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField 

CGRect rc = [textField bounds];
rc = [textField convertRect:rc toView:self.finishingTableView];
CGPoint pt = rc.origin;
pt.x = 0;
if(rc.origin.y > 200)
    pt.y -=  150;
else
    pt.y -= rc.origin.y;
    [self.finishingTableView setContentOffset:pt animated:YES];

【问题讨论】:

你能用[UITableView -scrollToRowAtIndexPath:atScrollPosition:animated:]完成你想要的吗? 【参考方案1】:

UITableView 有一个方法:

- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated

您可以随意使用scrollPosition 来获得想要的结果。

【讨论】:

关于此方法,我只能在键盘显示时调用它,因为当键盘不显示时,我当前的代码没有问题。 我对 scrollToRowAtIndexPath 的唯一问题是它第一次将选定的 UITableViewCell 移动到中间或顶部,这很好......但是如果用户选择的东西不是最后一个单元格,它会给我带来不希望的结果... 我也刚刚使用 UITableViewScrollPositionMiddle 进行了测试,如果我在 UITableView 的下半部分选择了一些东西,它会导致同样的问题,它不会滚动到中间位置,当你点击输入时它会失去 UITextField 焦点.

以上是关于如何将 UITableViewCell 滚动到特定位置?的主要内容,如果未能解决你的问题,请参考以下文章