表格折叠

  • 通过改变分段的行数实现分段的折叠与打开。分段处于折叠状态时,设置分段的行数为 0。

1、分段折叠状态数组初始化

// 声明记录折叠状态数组
@property(nonatomic, retain)NSMutableArray *foldStatusArray;

// 初始化记录折叠状态数组
foldStatusArray = [[NSMutableArray alloc] init];

// 给分段折叠状态数组赋初值,状态值为 1 时,分段折叠
for (int i = 0; i < myDataArray.count; i++) {
    [foldStatusArray addObject:[NSNumber numberWithBool:YES]];
}

2、UITableView 协议方法

// 设置行数,UITableViewDataSource 协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    // 获取分段的折叠状态,foldStatusArray 存放的是 NSNumber 类型的值
    BOOL isFold = [[foldStatusArray objectAtIndex:section] boolValue];

    if (isFold) {

        // 分段处于折叠状态时,设置分段的行数为 0
        return 0;
    }
    return [[myDataArray objectAtIndex:section] count];
}

// 设置分段头标题高度,UITableViewDelegate 协议方法
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 30;
}

// 设置分段头标题视图,UITableViewDelegate 协议方法
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {

    UIButton *headerButton = [UIButton buttonWithType:UIButtonTypeCustom];
    headerButton.frame = CGRectMake(0, 0, tableView.frame.size.width, 30);
    headerButton.backgroundColor = [UIColor orangeColor];

    headerButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    headerButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    headerButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    headerButton.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    headerButton.layer.borderWidth = 1;

    // 设置分段头标题显示内容
    [headerButton setTitle:[NSString stringWithFormat:@" %c", (char)('A' + section)] forState:UIControlStateNormal];

    // 设置分段的 tag 值
    headerButton.tag = 100 + section;

    // 添加分段头标题点击响应事件
    [headerButton addTarget:self action:@selector(headerButtonClick:) forControlEvents:UIControlEventTouchUpInside];        
    return headerButton;
}

3、头标题点击响应事件

- (void)headerButtonClick:(UIButton *)button {

    // 获取分段的折叠状态,foldStatusArray 存放的是 NSNumber 类型的值
    BOOL isFold = [[foldStatusArray objectAtIndex:button.tag - 100] boolValue];

    // 改变分段的折叠状态
    foldStatusArray[button.tag - 100] = [NSNumber numberWithInt: isFold ? NO : YES];

    // 重载分段
    [myTableView reloadSections:[NSIndexSet indexSetWithIndex:button.tag - 100] withRowAnimation:UITableViewRowAnimationAutomatic];
}

4、运行效果图

  • 1213778-20180805113208795-1792911865.png ------ 1213778-20180805113224839-136759974.png

转载于:https://www.cnblogs.com/CH520/p/9420421.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值