2010-04-21 74 views
7

我正在使用iPhone SDK 3.1.3。我有一个UITableViewController从其他控制器获取数据。表格视图作为子视图添加到主视图中,但框架已设置为不可见。通过点击按钮,表格视图框架被更新并且在主视图上滑动。UITableView滚动到特定位置

表格视图出现,我滚动到最后一行。如果我选择最后一行,我会用更多的数据重新加载表格。该表获得更多数据更新。一切工作正常,除了滚动位置始终是顶部。

我需要滚动位置是我点击加载更多数据的最后一行。我保存滚动位置并在加载更多数据后调用下面的代码。它执行没有问题,但滚动位置始终是最高的。

[theTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:savedScrollPosition inSection:0] atScrollPosition:savedScrollPosition animated:NO]; 

上述似乎没有效果。 ViewWillAppear:ViewDidAppear:不会触发,我被告知如果视图控制器在代码中被实例化,情况就是这样,它们不会触发。请重新加载表格([theTableView reloadData])后,请帮助我确定如何以及何时设置滚动位置,以便它位于我点击的行上。

代码重新加载表视图&滚动

////performAction will notify the tableviewcontroller which will result in didPerformAction being called 
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    if (indexPath.row == lastRow) 
    { 
     savedScrollPosition = lastRow; 
     //perform the action 
     [controller performAction]; 
    } 
} 

- (void) didPerformAction:(NSNotification *)obj 
{ 
    [theTableView reloadData]; 
    [theTableView 
    scrollToRowAtIndexPath: [NSIndexPath indexPathForRow:savedScrollPosition inSection:0] 
    atScrollPosition:UITableViewScrollPositionBottom 
    animated:NO]; 
} 

回答

28

这似乎这样的伎俩。

[theTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:savedScrollPosition inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO]; 
CGPoint point = theTableView.contentOffset; 
point .y -= theTableView.rowHeight; 
theTableView.contentOffset = point; 
+2

这个语句中的savedScrollPosition是什么 – 2015-07-10 08:31:14

0

如果这是真实的代码,假设theTableView不是nil那里,你应该得到一个警告说,因为scrollToRowAtIndexPath是“可以不回应......”拼错了。

其次,atScrollPosition参数需要一个UITableViewScrollPosition枚举值,指示屏幕上希望目标行的位置。

试试这个:

[theTableView scrollToRowAtIndexPath: 
       [NSIndexPath indexPathForRow:savedScrollPosition inSection:0] 
       atScrollPosition:UITableViewScrollPositionBottom 
       animated:NO]; 
+0

对不起,这是一个错字。我编辑过它。 好吧,我不想滚动到底部。我需要滚动到我点击的那一行,每次都是中间的,但不是中间的。尽管如此,我尝试了这一点,并且很奇怪,它仍然处于顶端。 – Dave 2010-04-21 18:52:00

+0

显示调用它的方法。在调用之前放置NSLogs,显示savedScrollPosition的值。 atScrollPosition不引用行号,而是引用屏幕上当前的相对位置。 – DyingCactus 2010-04-21 18:59:12

+0

哦,我明白了。我更新了代码。 – Dave 2010-04-21 19:30:28

10

它会更好看,滚动条的位置将保持固定的,如果你可以插入行,而不是调用reloadData的。

[theTableView beginUpdates]; 
[theTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:animation]; 
// make sure the dataSource will return new rows before calling endUpdates 
[theTableView endUpdates]; 

而不是使用的UITableView滚动,你可以使用UIScrollView的滚动:

savedOffset = [theTableView contentOffset]; 

然后恢复:

[theTableView setContentOffset:savedOffset]; 
+0

哦谢谢,我刚刚发布了与您的答案基本相同的答案,设置contentOffset。感谢您的插入行提示。 – Dave 2010-04-21 21:14:30

相关问题