1. 程式人生 > >iOS開發-UI控制元件:可摺疊展開的UITableView

iOS開發-UI控制元件:可摺疊展開的UITableView

在之前的專案中自己寫了一個可以摺疊展開的UITableView. 思路如下:

1. 使用一個字典儲存Table中每個Section開啟&摺疊的狀態, 然後在下面的方法中, 字典返回1則展開cell, 反之摺疊cell  

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section{//根據表頭,到總陣列中,篩選出臨時陣列,確定數量
    [[self classArr] objectAtIndex:section];
    int rowCount = 0;
    for (int i = 0; i < [[self dataArr] count]; i ++) {
        CellModel *model = [[self dataArr] objectAtIndex:i];
        if (model == [[self classArr] objectAtIndex:section]) {
            rowCount ++;
        }
    }
    NSString *key = [NSString stringWithFormat:@"%d", (int)section];
    BOOL folded = [[[self switchDict] objectForKey:key] boolValue];
    return folded?rowCount:0;
}
2.自定義Table的HeaderView(即SectionView), 新增一個按鈕, 通過代理將按鈕的點選事件返會到Table中, 改變對應字典的值, 然後重新整理Table, 就OK了.

NKFoldSectionView.h:

#import <UIKit/UIKit.h>
#import "CellModel.h"

@class NKFoldSectionView;

@protocol NKFoldSectionViewDelegate <NSObject>
- (void)foldHeaderInSection:(NSInteger)SectionHeader;
@end

@interface NKFoldSectionView : UITableViewHeaderFooterView
@property(nonatomic, assign) NSInteger section;/** selected section */
@property(nonatomic, weak) id<NKFoldSectionViewDelegate> delegate;/** delegate */
- (void)setSectionViewWithModel:(CellModel *)model section:(NSInteger)section;
@end

NKFoldSectionView.m:

#import "NKFoldSectionView.h"

@interface NKFoldSectionView ()
@property(nonatomic, weak)   UILabel *titleLabel;/** title */
@property(nonatomic, weak)   UIButton *coverBtn;
@end

@implementation NKFoldSectionView{
    BOOL _created;
}

- (void)setSectionViewWithModel:(CellModel *)model section:(NSInteger)section{
    //1.init UI
    if (!_created) {
        [self creatUI];
    }
    //2.setup data to UI
    _titleLabel.text = [NSString stringWithFormat:@"%d", model.classNo];
    
    _section = section;
}

- (void)creatUI {
    _created = YES;
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.textColor = [UIColor blackColor];
    [self.contentView addSubview:titleLabel];
    _titleLabel = titleLabel;
    
    UIButton *coverBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [coverBtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.contentView addSubview:coverBtn];
    _coverBtn = coverBtn;
    
    //Creat your UI in here...
}

- (void)btnClick:(UIButton *)btn {
    if ([self.delegate respondsToSelector:@selector(foldHeaderInSection:)]) {
        [self.delegate foldHeaderInSection:_section];
    }
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    _titleLabel.frame = CGRectMake(5, 0, self.contentView.frame.size.width, 60);
    _coverBtn.frame = CGRectMake(0, 0, self.contentView.frame.size.width, self.contentView.frame.size.height);
}
@end