Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

iOS 開發:用 TableView 實作 QQ 風格的分組折疊與展開

編輯:關於 Android 程式設計

QQ 的聯絡人清單點一下分組標題就能收合或展開,這個效果在 UITableView 上實作起來比想像中簡單。一開始容易想到的路子是「在 cell 裡再嵌一個 UITableView」,但巢狀 TableView 的滾動與重用問題會讓你頭痛很久。

換個角度想就通了:折疊與展開本質上只是「改變某個 section 的 row 數量」。而點擊的入口,用 section 的 HeaderView 加上手勢判斷剛剛好。

核心資料結構

需要三個屬性:資料源、各組標題,以及一個記錄「哪一組目前是展開狀態」的字典。

@property (nonatomic, strong) UITableView *myTableView;
@property (nonatomic, strong) NSMutableArray *listArray;        // 資料源
@property (nonatomic, strong) NSMutableArray *titlesArray;      // 分組名稱
@property (nonatomic, strong) NSMutableDictionary *openSectionDict;  // 記錄展開狀態

初始化與假資料

- (void)viewDidLoad {
    [super viewDidLoad];

    _myTableView = [[UITableView alloc] initWithFrame:self.view.frame
                                               style:UITableViewStyleGrouped];
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    [self.view addSubview:_myTableView];

    self.openSectionDict = [[NSMutableDictionary alloc] init];
    [self setUpData];
}

- (void)setUpData {
    self.listArray = [NSMutableArray new];
    self.titlesArray = [NSMutableArray new];

    for (int i = 0; i < 5; i++) {
        [self.titlesArray addObject:[NSString stringWithFormat:@"section %d", i]];

        NSMutableArray *array = [NSMutableArray new];
        for (int j = 0; j < 4; j++) {
            [array addObject:[NSString stringWithFormat:@"row %d", j]];
        }
        [self.listArray addObject:array];
    }
}

關鍵:讓 row 數量隨展開狀態改變

整個效果的樞紐就在這個方法——如果該組在字典中記為未展開,就回傳 0 個 row:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSInteger opened = [[self.openSectionDict valueForKey:[NSString stringWithFormat:@"%ld", (long)section]] integerValue];
    return opened == 0 ? 0 : 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL_ID"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                     reuseIdentifier:@"CELL_ID"];
    }
    cell.textLabel.text = [NSString stringWithFormat:@"row %ld", (long)indexPath.row];
    return cell;
}

HeaderView:箭頭狀態與點擊手勢

用 tag 把 section 編號藏在 HeaderView 上,點擊時就能反推是哪一組被按了:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;   // 避免 Grouped 樣式出現預設間距
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(
            0, 0, tableView.bounds.size.width, 40)];
    view.backgroundColor = [UIColor whiteColor];
    view.tag = KTAG + section;   // 用 tag 記住 section 編號

    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(
            20, 0, view.bounds.size.width, view.bounds.size.height)];
    label.text = self.titlesArray[section];
    [view addSubview:label];

    BOOL opened = [[self.openSectionDict valueForKey:
            [NSString stringWithFormat:@"%ld", (long)section]] integerValue] != 0;

    UIImageView *arrow = [[UIImageView alloc] initWithFrame:
            opened ? CGRectMake(10, (view.bounds.size.height - 7) / 2, 10, 7)
                   : CGRectMake(10, (view.bounds.size.height - 10) / 2, 7, 10)];
    arrow.image = opened ? [UIImage imageNamed:@"Triangle_down_gray"]
                         : [UIImage imageNamed:@"Triangle_right_gray"];
    [view addSubview:arrow];

    UITapGestureRecognizer *tap =
            [[UITapGestureRecognizer alloc] initWithTarget:self
                                                  action:@selector(collegeTaped:)];
    [view addGestureRecognizer:tap];

    return view;
}

點擊後只刷新該 section

- (void)collegeTaped:(UITapGestureRecognizer *)sender {
    NSString *key = [NSString stringWithFormat:@"%ld", (long)(sender.view.tag - KTAG)];

    // 狀態取反
    if ([[self.openSectionDict objectForKey:key] integerValue] == 0) {
        [self.openSectionDict setObject:@"1" forKey:key];
    } else {
        [self.openSectionDict setObject:@"0" forKey:key];
    }

    NSIndexSet *set = [NSIndexSet indexSetWithIndex:sender.view.tag - KTAG];
    [self.myTableView reloadSections:set withRowAnimation:UITableViewRowAnimationFade];
}

這裡用 reloadSections:withRowAnimation: 而不是 reloadData,有兩個好處:只重繪受影響的那一組,效能更好;而且能帶入 Fade 動畫,折疊的過渡不會硬邦邦。

成果

可以再加強的地方

目前 openSectionDict 用 0/1 表示收合狀態,若日後要做「同一時間只能展開一組」的手風琴效果,只要在切換時先把其他 key 全部設為 0 即可。另外若資料是異步載入,記得在回來後呼叫 reloadData,並把 openSectionDict 的內容保留下來,使用者捲動時才不會跳回全收合的狀態。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved