購物車、多選刪除這類功能幾乎每個 App 都會遇到。邏輯寫起來不難,但一捲動列表就會出問題:cell 被復用後,先前勾選的狀態莫名消失了。這是 UITableView 復用機制與「狀態存在 view 上」這個習慣共同造成的經典陷阱。
UITableView 為了效能只會配置有限數量的 cell,滑出畫面的 cell 會被回收,滑回來時則被重用。如果你把「是否選中」這個狀態存在 cell 的按鈕上,那麼 cell 一旦回收,狀態就跟著不見了。
用一個 NSMutableSet 來記錄已選中的項目。它與 NSArray 類似,但提供了 addObject: 與 removeObject: 兩個方法可直接增刪元素,並以 containsObject: 進行查詢。勾選時把 indexPath 或按鈕 tag 加入集合,cell 復用時再依集合內容還原狀態即可。
#pragma mark – 返回每一行顯示的內容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ShoppingCartTableViewCell *cell = (ShoppingCartTableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"ShoppingCartTableViewCell"];
if (cell == nil) {
cell = [[[NSBundle mainBundle] loadNibNamed:@"ShoppingCartTableViewCell" owner:self options:nil] lastObject];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
GoodCartInfoModel *model = dataArray[indexPath.row];
[cell addTheValue:model];
cell.delegate = self;
cell.selectButton.tag = 100 + indexPath.row;
cell.selectButton.selected = NO;
[cell.selectButton addTarget:self action:@selector(selectButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
// 依集合內容還原勾選狀態
if ([btnStatusSet containsObject:[NSString stringWithFormat:@"%d", (100 + indexPath.row)]]) {
cell.selectButton.selected = YES;
[cell.selectButton setImage:[UIImage imageNamed:@"btn_select_default"] forState:(UIControlStateNormal)];
}
return cell;
}
- (void)selectButtonClick:(UIButton *)btn {
if (btn.selected == NO) {
btn.selected = YES;
[btnStatusSet addObject:[NSString stringWithFormat:@"%d", btn.tag]];
} else {
btn.selected = NO;
[btnStatusSet removeObject:[NSString stringWithFormat:@"%d", btn.tag]];
}
}
selected 設為 NO,再依集合判斷是否設為 YES,否則會殘留上一筆資料的狀態。100 + indexPath.row 這種寫法在資料排序、刪除後容易錯位,建議直接用 model 的唯一識別碼(如商品 ID)當作集合元素。一句話總結:cell 只是「畫面」,狀態應該屬於「資料層」。把選中狀態存在集合或 model 裡,復用問題自然迎刃而解。