点击显示/折叠UITableView的Cell效果

想法:最初显示的是tableView的所有分区头,默认每个分区有0行, 点击分区头,给所在分区插入数据并reloadData

  • (1)定义一个自定义DataModel类,记录cell的点击状态
@interface DataModel : NSObject
 //分组头上的题目
@property (nonatomic) NSString *sectionTitle;
//当前分组的展开状态  fold 折叠
@property (nonatomic) BOOL fold;
//section的子元素@property (nonatomic) NSArray *rowDataArr;
@end
  • (2)自定义一个TableViewHeaderFooterView
    添加扩展:
@interface SectionHeaderView : UITableViewHeaderFooterView
@property (nonatomic) UIButton *btn;
@property (nonatomic) NSInteger section;
@property (nonatomic, copy) void(^btnClicked)(NSInteger section);
@end

方法实现:
@implementation SectionHeaderView
- (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier{
self = [super initWithReuseIdentifier:reuseIdentifier];
if (self) {
//添加点击手势
UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickBtn:)];
[self.contentView addGestureRecognizer:tapGR];
}
return self;
}
- (void)clickBtn:sender{
!_btnClicked ?: _btnClicked(_section);
}
@end

  • (3)在UIViewController中
    [ 有一个用来显示数据的数组 ]
    @property (nonatomic) NSArray *dataList;
    [tableView分区个数]
    DataModel *model = self.dataList[section]; 
   //根据分组的状态标识 来决定行数到底多少
    return model.fold ? 0 : model.rowDataArr.count;

[在分区头的方法里]
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
SectionHeaderView *v = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"SectionHeaderView"];
v.section = section;
[v setBtnClicked:^(NSInteger section) {
NSLog(@"%ld", section);
DataModel *model = _dataList[section];
//展开状态等于自身的反选
model.fold = !model.fold;
NSMutableArray *arr = [NSMutableArray new];
for (int i = 0; i < model.rowDataArr.count; i++) {
[arr addObject:[NSIndexPath indexPathForRow:i inSection:section]];
}
if (model.fold) {
//折叠, 即删除cell
[tableView deleteRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationFade];
}else{
//展开, 即增加cell
[tableView insertRowsAtIndexPaths:arr withRowAnimation:UITableViewRowAnimationFade];
}
}];
return v;
}

你可能感兴趣的:(点击显示/折叠UITableView的Cell效果)