iOS开发-UI控件:可折叠展开的UITableView

来源:互联网 发布:软件实施的自我介绍 编辑:程序博客网 时间:2024/04/29 11:08

在之前的项目中自己写了一个可以折叠展开的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


Demo地址: https://github.com/Nikolilol/NKFoldTableView

0 0
原创粉丝点击