[英]UITableView scrolling to specific position
我正在使用iPhone SDK 3.1.3。 我有一個UITableViewController
從另一個控制器獲取數據。 表視圖作為子視圖添加到主視圖中,但框架已設置為不可見。 更新表視圖框,並通過點擊按鈕使其在主視圖上滑動。
出現表格視圖,我滾動到最后一行。 如果我選擇最后一行,我會用更多數據重新加載表。 該表隨着更多數據而更新。 除了滾動位置始終是頂部之外,一切正常。
我需要滾動位置是我點擊以加載更多數據的最后一行。 我保存滾動位置並在加載更多數據后調用以下代碼。 它執行沒有問題,但滾動位置始終是頂部。
[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];
}
這似乎可以解決問題。
[theTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:savedScrollPosition inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
CGPoint point = theTableView.contentOffset;
point .y -= theTableView.rowHeight;
theTableView.contentOffset = point;
如果您可以插入行而不是調用reloadData,它看起來會更好並且滾動位置將保持不變。
[theTableView beginUpdates];
[theTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:animation];
// make sure the dataSource will return new rows before calling endUpdates
[theTableView endUpdates];
您可以使用UIScrollView滾動而不是使用UITableView滾動:
savedOffset = [theTableView contentOffset];
然后恢復:
[theTableView setContentOffset:savedOffset];
如果這是實際的代碼並且假設theTableView不是nil那么,你應該收到警告說“可能不響應......”因為scrollToRowAtIndexPath拼寫錯誤。
其次,atScrollPosition參數需要一個UITableViewScrollPosition枚舉值,指示屏幕上您希望目標行定位的位置。
試試這個:
[theTableView scrollToRowAtIndexPath:
[NSIndexPath indexPathForRow:savedScrollPosition inSection:0]
atScrollPosition:UITableViewScrollPositionBottom
animated:NO];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.