reloadData 會重載整個表格,導致滾動位置重置、動畫閃爍、性能開銷大。針對單行/多行變更,應使用 reloadRowsAtIndexPaths:withRowAnimation: 實現精準局部更新。
- (void)reloadRowsAtIndexPaths:(NSArray *)indexPaths
withRowAnimation:(UITableViewRowAnimation)animation;
- (void)updateRowAtIndex:(NSInteger)row inSection:(NSInteger)section {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
[self.tableView reloadRowsAtIndexPaths:@[indexPath]
withRowAnimation:UITableViewRowAnimationAutomatic];
}
- (void)updateRowsAtIndexes:(NSIndexSet *)indexSet inSection:(NSInteger)section {
NSMutableArray *indexPaths = [NSMutableArray array];
[indexSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
[indexPaths addObject:[NSIndexPath indexPathForRow:idx inSection:section]];
}];
[self.tableView reloadRowsAtIndexPaths:indexPaths
withRowAnimation:UITableViewRowAnimationFade];
}
| 常量 | 效果 | 推薦場景 |
|---|---|---|
UITableViewRowAnimationAutomatic | 系統自動選擇(通常為 Fade) | 通用、無特殊要求 |
UITableViewRowAnimationFade | 淡入淡出 | 數據內容替換、狀態切換 |
UITableViewRowAnimationRight/Left | 從右/左滑入 | 側邊欄展開、抽屉效果 |
UITableViewRowAnimationTop/Bottom | 從頂/底滑入 | 列表頂部/底部插入 |
UITableViewRowAnimationMiddle | 從中間擴展/收縮 | 分組展開折疊 |
UITableViewRowAnimationNone | 無動畫 | 高頻更新、性能敏感 |
- (void)updateItems:(NSArray- *)newItems {
NSMutableArray *indexPathsToReload = [NSMutableArray array];
for (NSUInteger i = 0; i < newItems.count; i++) {
Item *newItem = newItems[i];
Item *oldItem = self.dataSource[i];
// 業務邏輯判斷是否真正變化
if (![newItem isEqual:oldItem]) {
self.dataSource[i] = newItem;
[indexPathsToReload addObject:[NSIndexPath indexPathForRow:i inSection:0]];
}
}
if (indexPathsToReload.count > 0) {
[self.tableView reloadRowsAtIndexPaths:indexPathsToReload
withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
// 插入
[self.tableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationRight];
// 刪除
[self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
// 移動
[self.tableView moveRowAtIndexPath:sourceIndexPath toIndexPath:destinationIndexPath];
[self.tableView performBatchUpdates:^{
[self.tableView reloadRowsAtIndexPaths:reloadPaths withRowAnimation:UITableViewRowAnimationAutomatic];
[self.tableView insertRowsAtIndexPaths:insertPaths withRowAnimation:UITableViewRowAnimationRight];
[self.tableView deleteRowsAtIndexPaths:deletePaths withRowAnimation:UITableViewRowAnimationLeft];
} completion:^(BOOL finished) {
// 完成回調
}];
reloadRowsAtIndexPaths 前未更新 dataSource → 崩潰或顯示舊數據。performBatchUpdates 合併多操作,保證動畫同步。精準局部刷新,是列表流暢體驗與性能優化的關鍵技能。