ios UITableView三级展开

有个多级展开的需求,但不是那种三层嵌套,是这个效果:

多级展开.gif

这样 我们只需要给Tableview的总的header 以及分区header 增加一个展开即可:

总的header 不会复用,所以给header 一个展开属性

typedef void (^LXExpandBlock)(BOOL isExpand);
@interface LXTableviewHeader : UIView
@property(nonatomic, assign)BOOL isExpand;
@property(nonatomic,copy)LXExpandBlock expandBlock;
@end

分区header 的复用把展开属性设置在对应的model里

#import <UIKit/UIKit.h>
@class LXSectionModel;
typedef void (^LXHeaderViewExpandBlock)(BOOL isExpand);
@interface LXHeadView : UITableViewHeaderFooterView
@property(nonatomic,strong)LXSectionModel *model;
@property(nonatomic,copy)LXHeaderViewExpandBlock enpandBlock;
@end
#import <Foundation/Foundation.h>

@interface LXSectionModel : NSObject
@property (nonatomic, copy) NSString *sectionTitle;
// 是否是展开的
@property (nonatomic, assign) BOOL isExpanded;

@property (nonatomic, strong) NSMutableArray *cellModels;
@end

整体头部展开是这样的


    LXTableviewHeader *header =[[LXTableviewHeader alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    __weak ViewController *weakSelf = self;
    header.expandBlock = ^( BOOL isExpand)
    {
        [weakSelf.tableView reloadData];
    };
    self.tableView.tableHeaderView = header;
    self.headerView = header;

分区头部展开处理过程

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    LXHeadView *view =[tableView dequeueReusableHeaderFooterViewWithIdentifier:kHeaderIdentifier];
    LXSectionModel *sectionModel = self.sectionDataSources[section];
    
    view.model = sectionModel;
    view.enpandBlock = ^(BOOL isExpanded)
    {
        [tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:0];
    };
    return view;
}

返回分区与返回cell个数的处理

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.headerView.isExpand ?self.sectionDataSources.count:0;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
      LXSectionModel *sectionModel = self.sectionDataSources[section];
    return sectionModel.isExpanded ? sectionModel.cellModels.count:0;
}
所有的展开与收起 额外计算,只需要刷新整体或者刷新分区即可,改变分区个数与分区内对应cell 个数,不需要对cell 做insert 或者delete操作。

demo 地址:UITableview三级展开
参考文章:UITableView分区展开与收起

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容