二级列表,一次只展开一个

网上的二级列表,QQ分组的demo比比皆是,但是适合自己的才是最好了,我自己写了个适合自己用的,记录一下吧。以后用到的话就直接commond + v了

先上gif图

gif.gif
  • 首先是数据
    NSArray *data = @[@{
                          @"title":@"世上事仿佛都经不起后来的推敲",
                          @"cellData":@[@{
                                            @"content":@"诸如,后来你变了"
                                            },
                                        @{
                                            @"content":@"后来我卷了"
                                            }]
                          },
                      @{
                          @"title":@"后来故人零落",
                          @"cellData":@[@{
                                            @"content":@"新人款款前来"
                                            },
                                        @{
                                            @"content":@"后来时光静默"
                                            },
                                        @{
                                            @"content":@"过往逆流成河"
                                            }]
                          },
                      @{
                          @"title":@"模糊的青天雨落",
                          @"cellData":@[@{
                                            @"content":@"遗失的年少轻彻"
                                            },@{
                                            @"content":@"此去的别后经年"
                                            },
                                        @{
                                            @"content":@"他乡的阁楼冷彻"
                                            }]
                          },
                      @{
                          @"title":@"我还倚着些微的坚强",
                          @"cellData":@[@{
                                            @"content":@"却已背离曾经的方向"
                                            },
                                        @{
                                            @"content":@"半盏酒后"
                                            },
                                        @{
                                            @"content":@"便是遗忘"
                                            }]
                          }];
  • 创建model
    HeaderModel.h
#import <Foundation/Foundation.h>
#import "CellModel.h"
@interface HeaderModel : NSObject
@property (nonatomic,copy) NSString *title;
@property (nonatomic,strong) NSArray *cellData;
@end

HeaderModel.m

#import "HeaderModel.h"

@implementation HeaderModel
MJCodingImplementation
+(NSDictionary *)mj_objectClassInArray
{
    return @{
             @"cellData":@"CellModel"
             };
}
@end

CellModel.h

#import <Foundation/Foundation.h>
#import "MJExtension.h"
@interface CellModel : NSObject
@property (nonatomic,copy) NSString *content;
@end

CellModel.m

#import "CellModel.h"
@implementation CellModel
MJCodingImplementation
@end
  • UIViewController
#import "ViewController.h"
#import "HeaderModel.h"
#import "Cell.h"
#import "CellModel.h"
#import "HeaderView.h"
@interface ViewController ()
<UITableViewDelegate,UITableViewDataSource,HeaderViewDelegate>
{
    int _currentRow;
    int _currentSection;
}
@property (nonatomic, strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray * headViewArray;
@property (nonatomic,strong) NSMutableArray *data;
@end

@implementation ViewController

-(NSMutableArray *)data
{
    if (!_data) {
        _data = [NSMutableArray array];
    }
    return _data;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.    
    self.data = [HeaderModel mj_objectArrayWithKeyValuesArray:data];
    
    self.headViewArray = [NSMutableArray array];
    int i = 0;
    for (HeaderModel *model in self.data) {
        HeaderView *headerView = [[HeaderView alloc]init];
        headerView.headerModel = model;
        headerView.delegate = self;
        headerView.index = i;
        i++;
        [self.headViewArray addObject:headerView];
    }
    
    
    [self.view addSubview:self.tableView];
}

  • 创建tableView
-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 10, self.view.width, self.view.height - 20) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return _tableView;
}

  • UITableviewDelegate---UITableviewDataSource

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

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return self.headViewArray[section];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    HeaderView* headView = self.headViewArray[section];
    HeaderModel *headerModel = self.data[section];
    return headView.open?headerModel.cellData.count:0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return [self.headViewArray count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Cell *cell = [Cell cellWithTableView:tableView];
    HeaderModel *headerModel = self.data[indexPath.section];
    CellModel *model = headerModel.cellData[indexPath.row];
    cell.model = model;
    return cell;
}
-(CGFloat)tableView:(UITableView*)tableView heightForRowAtIndexPath:(NSIndexPath*)indexPath
{
    return 50;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"click---%ld section and %ld row",(long)indexPath.section,(long)indexPath.row);
}
#pragma mark - HeadViewdelegate
-(void)selectedWith:(HeaderView *)view{
    _currentRow = -1;
    if (view.open) {
        for(int i = 0;i<[self.headViewArray count];i++)
        {
            HeaderView *head = [self.headViewArray objectAtIndex:i];
            head.open = NO;
            [UIView animateWithDuration:0.15 delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
                head.backBtn.layer.transform = CATransform3DMakeRotation(0, 0, 0, 1);
            } completion:NULL];
        }
        [_tableView reloadData];
        return;
    }
    _currentSection = (int)view.index;
    [self reset];
}
//界面重置
- (void)reset
{
    for(int i = 0;i<[self.headViewArray count];i++)
    {
        HeaderView *head = [self.headViewArray objectAtIndex:i];
        if(head.index == _currentSection)
        {
            head.open = YES;
            [UIView animateWithDuration:0.15 delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
                head.backBtn.layer.transform = CATransform3DMakeRotation(M_PI, 0, 0, 1);
            } completion:NULL];
        }else {
            [UIView animateWithDuration:0.15 delay:0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
                head.backBtn.layer.transform = CATransform3DMakeRotation(0, 0, 0, 1);
            } completion:NULL];
            head.open = NO;
        }
    }

    [_tableView reloadData];
}
  • 创建SectionHeaderView
    HeaderView.h
#import <UIKit/UIKit.h>
@class HeaderView,HeaderModel;
@protocol HeaderViewDelegate <NSObject>
-(void)selectedWith:(HeaderView *)view;
@end
@interface HeaderView : UIView
@property (nonatomic,weak) id<HeaderViewDelegate> delegate;
@property(nonatomic, assign) NSInteger index;
@property(nonatomic, assign) BOOL open;
@property(nonatomic, retain) UIButton* backBtn;
@property(nonatomic, strong) HeaderModel * headerModel;

@end

HeaderView.m

#import "HeaderView.h"
#import "UIView+Extension.h"
#import "HeaderModel.h"
@interface HeaderView()
@property (nonatomic,strong) UIView *backView;
@property (nonatomic,weak) UILabel *label;

@end
@implementation HeaderView
-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        _open = NO;
        
        CGFloat titleFont = 15;

        self.backgroundColor = [UIColor whiteColor];
        
        UIView *backView = [[UIView alloc]init];
        backView.backgroundColor = [UIColor whiteColor];
        self.backView = backView;
        [self addSubview:backView];
        
        //时间
        UILabel *label = [[UILabel alloc]init];
        label.font = [UIFont systemFontOfSize:titleFont] ;
        label.textColor = [UIColor blackColor];
        label.textAlignment = NSTextAlignmentLeft;
        [backView addSubview:label];
        self.label = label;
        
        //箭头
        UIButton* btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn addTarget:self action:@selector(doSelected) forControlEvents:UIControlEventTouchUpInside];
        [self addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(doSelected)]];
        [btn setImage:[UIImage imageNamed:@"向下箭头-4"] forState:UIControlStateNormal];
        [btn.imageView setContentMode:UIViewContentModeScaleAspectFill];
        [backView addSubview:btn];
        self.backBtn = btn;
    }
    return self;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    //位置
    self.backView.frame = CGRectMake(0, 5, self.width, self.height - 10);
    self.label.frame = CGRectMake(10, (self.backView.height - 40)/2, self.backView.width - 60, 40);

    self.backBtn.frame = CGRectMake(self.width - self.height +10, 0, self.height - 10, self.height - 10);
}

-(void)setHeaderModel:(HeaderModel *)headerModel
{
    _headerModel = headerModel;
    self.label.text = headerModel.title;
    
}
-(void)doSelected{
    if (_delegate && [_delegate respondsToSelector:@selector(selectedWith:)]){
        [_delegate selectedWith:self];
    }
}
  • 创建Cell
    Cell.h
#import <UIKit/UIKit.h>
@class CellModel;
@interface Cell : UITableViewCell
+(instancetype)cellWithTableView:(UITableView *)tableView;
@property (nonatomic,strong) CellModel *model;
@end

Cell.m

#import "Cell.h"
#import "CellModel.h"
#import "UIView+Extension.h"
@interface Cell ()

@property (nonatomic,weak) UILabel *piCiLabel;

@end
@implementation Cell
+(instancetype)cellWithTableView:(UITableView *)tableView
{
    static NSString *CellID = @"Cell";
    Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellID];
    if (cell == nil) {
        cell = [[Cell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return cell;
}
- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        // 添加自己可能显示的所有子控件
        self.backgroundColor = [UIColor whiteColor];
        
        UILabel *piCiLabel = [[UILabel alloc]init];
        piCiLabel.font = [UIFont systemFontOfSize:14] ;
        piCiLabel.textColor = [UIColor lightGrayColor];
        piCiLabel.textAlignment = NSTextAlignmentLeft;
        [self.contentView addSubview:piCiLabel];
        self.piCiLabel = piCiLabel;
    }
    return self;
}

-(void)setModel:(CellModel *)model
{
    _model = model;
    self.piCiLabel.text = model.content;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    self.piCiLabel.frame = CGRectMake(20, (self.height - 40)/2, self.width - 25, 40);
}
- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end

最近发现一个问题,就是如果列表数据多了的话,点击最下面的二级列表,tableview就会自动回滚到最上面去,一直以为是刷新了整个tableview导致的,后来发现并不是,给tableview添加这三个属性就好了

      _tableView.estimatedRowHeight = 0;
      _tableView.estimatedSectionHeaderHeight = 0;
      _tableView.estimatedSectionFooterHeight = 0;

最后附上gitHub地址😀,觉得好用的,请给个星哦demo传送门

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 222,183评论 6 516
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,850评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 168,766评论 0 361
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,854评论 1 299
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,871评论 6 398
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,457评论 1 311
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,999评论 3 422
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,914评论 0 277
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,465评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,543评论 3 342
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,675评论 1 353
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,354评论 5 351
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 42,029评论 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,514评论 0 25
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,616评论 1 274
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 49,091评论 3 378
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,685评论 2 360

推荐阅读更多精彩内容

  • 想写一部小说~
    关山月_9fd9阅读 187评论 0 0
  • 龚小华 不管是繁花似锦的春天,还是烈烈日...
    都梁听雨阅读 1,073评论 1 10
  • 为什么要翻译 简单的说翻译这个主要是因为这本书没有中文版,为了给自己找到一个持续的动力,不至于看到学期一半就把他丢...
    yuruilee阅读 355评论 0 0