要在資料載入完成後把列表捲到最底端,做法依 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];
}
同樣在 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。這在聊天介面這類「永遠停在最新訊息」的場景特別好用。