通訊錄這類需要勾選多筆資料的清單,常會需要「多選」與「全選」功能。以下示範如何在 UITableView 中實作。
核心思路是在點擊某列時,切換該列對應資料的「勾選狀態」,並同步更新 cell 的顯示。
- (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 屬性 checked 與對應的 setChecked: 方法,用來控制勾選樣式。
透過一個按鈕切換,遍歷所有可見列,依按鈕標題判斷要全部勾選還是全部取消。
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];
}
}
整個功能的資料真相來源(single source of truth)是 contacts 陣列中每一筆 dictionary 的 "checked" 欄位;cell 只是呈現結果的檢視。因此無論勾選或全選,都要先更新資料、再更新畫面,這樣在 cell 被回收重複使用時,狀態才不會錯亂。