2010-04-21 116 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