整張表刷新用 reloadData 雖然方便,但代價是全部 cell 被重建:捲動位置可能跳動、cell 上的動畫會中斷、輸入中的狀態會遺失。若只是某幾列的內容變了,用局部刷新會好得多。
基本寫法如下:
NSIndexPath *indexPath_1 = [NSIndexPath indexPathForRow:1 inSection:0];
NSArray *indexArray = [NSArray arrayWithObject:indexPath_1];
[regTableView reloadRowsAtIndexPaths:indexArray
withRowAnimation:UITableViewRowAnimationNone];
withRowAnimation 可用的選項有 None、Right、Left、Top、Bottom、Middle、Fade 與 Automatic,依視覺需求挑選即可。
1. 務必先更新資料來源。reloadRowsAtIndexPaths: 會立刻觸發 tableView:cellForRowAtIndexPath:,若此時你的 data source 還是舊值,畫面就會顯示錯誤內容。順序永遠是「先改資料,再刷新」。
2. 注意 indexPaths 必須有效。傳入超出 section 範圍或 row 數量的 indexPath,會直接拋出 NSInternalInconsistencyException。若資料量可能變動,改用 reloadSections: 或先確認 count。
3. 動畫要放在呼叫 stack 之外。若在已有的動畫區塊(例如 beginUpdates / commitAnimations 之間)呼叫 reloadRows,UITableView 會抱怨嵌套的捲動動畫。把刷新移到動畫完成之後即可。
如果只是 cell 內某個小元件的內容變了,連 reloadRows 都不必——直接取得該 cell 並改動它的 subview 最省事:
UITableViewCell *cell = [regTableView cellForRowAtIndexPath:indexPath_1]; cell.detailTextLabel.text = @"新的內容";
若資料是插入或刪除而非修改,則改用 insertRowsAtIndexPaths:withRowAnimation: 與 deleteRowsAtIndexPaths:withRowAnimation:,並記得把一連串操作包在 beginUpdates / endUpdates 之間,讓表格一次完成版面計算,避免跳動。