您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 詳解:為 UITableView 實作全選與多選功能

編輯:iOS 相關資訊

通訊錄這類需要勾選多筆資料的清單,常會需要「多選」與「全選」功能。以下示範如何在 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 被回收重複使用時,狀態才不會錯亂。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved