表格折叠

  • 通过改变分段的行数实现分段的折叠与打开。分段处于折叠状态时,设置分段的行数为 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、运行效果图

  • ------

猜你喜欢

转载自www.cnblogs.com/CH520/p/9420421.html