已知 indexPath.row 需修改對應 Cell 的 imageView.image,嘗試 [self.tableView cellForRowAtIndexPath:0] 語法錯誤(參數需 NSIndexPath*)。
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
// 或 Swift
let indexPath = IndexPath(row: row, section: section)
// Objective-C
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if (cell) {
cell.imageView.image = [UIImage imageNamed:@"image"]; // 不需 .png 後綴,支援 @2x/@3x 自動選擇
}
// Swift
if let cell = tableView.cellForRow(at: indexPath) {
cell.imageView?.image = UIImage(named: "image")
}
cellForRowAtIndexPath 返回 nil 若 Cell 已離螢幕(被複用)。reloadRowsAtIndexPaths,讓 cellForRowAtIndexPath 重新配置:
// 資料模型
self.items[row].imageName = "new_image"
// 重載單行 (帶動畫)
[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
- (void)updateCellImageAtRow:(NSInteger)row section:(NSInteger)section imageName:(NSString *)imageName {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:section];
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
if (cell) {
// 即時修改 (無動畫)
cell.imageView.image = [UIImage imageNamed:imageName];
} else {
// Cell 不可見,更新資料模型等待複用時配置
self.dataSource[row].imageName = imageName;
}
}
image 而非 image.png,系統自動匹配 @2x/@3x。performBatchUpdates 包裹多個 reload/insert/delete。理解 cellForRowAtIndexPath 僅返回可見 Cell 實例,配合資料模型驅動,是 TableView 穩定高效操作的核心。