您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS:讓 UITableView 捲動到最底部的 cell

編輯:iOS 開發綜合

要在資料載入完成後把列表捲到最底端,做法依 section 的結構分成兩種情況。

情況一:多個 section,每個 section 只有一筆

在 [_diaryTableView reloadData] 之後加上:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0
                                          inSection:_contents.count - 1];
if (indexPath.section < [self numberOfSectionsInTableView:_diaryTableView]) {
    [_diaryTableView scrollToRowAtIndexPath:indexPath
                           atScrollPosition:UITableViewScrollPositionBottom
                                   animated:YES];
}

情況二:只有一個 section,內含多筆

同樣在 reloadData 之後:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:_contents.count - 1 inSection:0];
if (indexPath.row < [_diaryTableView numberOfRowsInSection:0]) {
    [_diaryTableView scrollToRowAtIndexPath:indexPath
                           atScrollPosition:UITableViewScrollPositionBottom
                                   animated:YES];
}

兩個實作上的提醒

第一,那個 if 判斷並非多餘。如果資料來源是 asynchronously 載入,reloadData 之後的實際行數可能還沒到位,直接捲動會讓 scrollToRowAtIndexPath: 收到一個超出範圍的 index path 而拋出例外。先夾一下邊界是低成本的自保。

第二,如果只是想讓內容貼齊底部、又不需要精確定位到某一列,更簡單的做法是把 tableView.scrollEnabled 保留,改用 contentInset 的 bottom 加上一個空白,或者直接把 tableFooterView 設為一個高度足夠的空白 view。這在聊天介面這類「永遠停在最新訊息」的場景特別好用。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved