在開發列表介面時,若每次資料變動都呼叫 reloadData 刷新整個 TableView,不僅效能不佳,畫面閃爍也會影響使用者體驗。這時,「局部刷新」就是更理想的做法——只更新真正改變的部分。
若只需更新某個分區,可使用 reloadSections:withRowAnimation:,並透過 NSIndexSet 指定要刷新的分區索引:
// 局部 section 刷新
NSIndexSet *nd = [[NSIndexSet alloc] initWithIndex:1]; // 刷新第二個 section
[tview reloadSections:nd withRowAnimation:UITableViewRowAnimationAutomatic];
若只需更新某一列的特定 Cell,則使用 reloadRowsAtIndexPaths:withRowAnimation:,並以 NSIndexPath 定位到明確的列:
// 局部 cell 刷新
NSIndexPath *te = [NSIndexPath indexPathForRow:2 inSection:0]; // 刷新第一個 section 的第二列
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:te, nil] withRowAnimation:UITableViewRowAnimationMiddle];
局部刷新有兩個關鍵角色:NSIndexSet 用於定位分區,NSIndexPath 則用於定位具體的列。善用這兩個工具搭配適當的動畫效果,不僅能提升效能,也能帶來更平順流暢的操作體驗。