在 UITableView 中實作多選與全選,常見做法是為每一列維護一個選取狀態,並在點擊時更新資料來源與 Cell 樣式。
在 didSelectRowAtIndexPath 中切換該列的選取狀態:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
Custom *cell = (Custom *)[tableView cellForRowAtIndexPath:indexPath];
NSUInteger row = [indexPath row];
NSMutableDictionary *dic = [contacts objectAtIndex:row];
if ([[dic objectForKey:@"checked"] isEqualToString:@"NO"]) {
[dic setObject:@"YES" forKey:@"checked"];
[cell setChecked:YES];
} else {
[dic setObject:@"NO" forKey:@"checked"];
[cell setChecked:NO];
}
}
在自訂 Cell 中可加入 BOOL 屬性與設定方法:
@property (nonatomic, assign) BOOL checked;
- (void)setChecked:(BOOL)checked {
_checked = checked;
// 更新勾選樣式
}
全選時,可遍歷可見或全部資料,將 checked 設為 YES:
NSArray *anArrayOfIndexPath = [NSArray arrayWithArray:[contactList indexPathsForVisibleRows]];
for (int i = 0; i != [contacts count]; i++) {
NSIndexPath *indexPath = [anArrayOfIndexPath objectAtIndex:i];
Custom *cell = (Custom *)[contactList cellForRowAtIndexPath:indexPath];
NSUInteger row = [indexPath row];
NSMutableDictionary *dic = [contacts objectAtIndex:row];
if ([[[(UIButton *)sender titleLabel] text] isEqualToString:@"全選"]) {
[dic setObject:@"YES" forKey:@"checked"];
[cell setChecked:YES];
} else {
[dic setObject:@"NO" forKey:@"checked"];
[cell setChecked:NO];
}
}
若需要跨頁或跨區段保持選取狀態,建議將選取狀態存在資料模型中,而不是只依賴 Cell 的視覺狀態。Cell 會被重用,若狀態只存在 Cell 上,捲動後可能會顯示錯誤。