tableViewCell的展开收起(自适应高度)

tableViewCell的展开收起+autolayout布局(自适应高度)

1、分析:

1、获取到点击事件(代理、block)
2、更新状态,
3、进行相应状态操作

2、viewController的处理
ViewController:
@property(nonatomic, strong) NSArray *infoArray; //数据
@property(nonatomic, strong) NSMutableArray *statusArray;//存储展开收起状态

不要忽略了这两句代码:

self.tableView.rowHeight = UITableViewAutomaticDimension;//自动调整高度
self.tableView.estimatedRowHeight = 150;//预估计高度
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    GPExtensionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    cell.titleLabel.text = self.dataSource[indexPath.row];
    NSNumber *status = self.statusArray[indexPath.row];
    [cell setCellExtensionStatus:status.boolValue infoString:self.infoArray[indexPath.row]];
    __weak typeof(self) weakSelf = self;
    cell.actionBlock = ^(BOOL status, UITableViewCell *cell){
        NSLog(@"status : %d",status);
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf extensionCell:cell status:status];
        });
       
    };
    return cell;
}

//修改展开状态

- (void)extensionCell:(UITableViewCell *)cell status:(BOOL)status {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    self.statusArray[indexPath.row] = status? @1 : @0;

    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
3、cell:

1)cell的xib文件
采用autolayout布局。若不是的话,使用本文章所说的这方式的话,还要补充对cell高度的计算、实现tableView获取高度的代理方法:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 0;
}

此外,若是autolayout设置得不合理也会影响系统自动计算高度,这就要考验你的约束布局啦

PS:autolayout布局不会使用,请自行补充学习。


2)cell的.h文件

typedef void (^extensionActinBlock)(BOOL status, UITableViewCell *cell);
@property(nonatomic, copy) extensionActinBlock actionBlock;
//设置cell内容
- (void)setCellExtensionStatus:(BOOL)status infoString:(NSString *)infoString;

3).m文件:

- (void)setCellExtensionStatus:(BOOL)status infoString:(NSString *)infoString {
    if (status) {
        [self.extensionButton setTitle:@"收起" forState:UIControlStateNormal];
    }else{
        [self.extensionButton setTitle:@"展开" forState:UIControlStateNormal];
        infoString = @"";
    }
    self.infoLabel.text = infoString;
}
//按钮的点击事件
- (IBAction)buttonClickAction:(UIButton *)sender {
    BOOL status = NO;
    if ([self.extensionButton.titleLabel.text isEqualToString:@"收起"]) {
        [self.extensionButton setTitle:@"展开" forState:UIControlStateNormal];
       
    }else{
        status = true;
        [self.extensionButton setTitle:@"收起" forState:UIControlStateNormal];
    }
    if (self.actionBlock) {
        self.actionBlock(status, self);
    }
}

你可能感兴趣的:(tableViewCell的展开收起(自适应高度))