iOS动态改变TableView Cell高度

本文介绍了一种在 iOS 开发中动态调整 TableViewCell 高度的方法。该方法通过预先创建 cell 并获取其内容视图的高度来确定 cell 的高度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

iOS动态改变TableView Cell高度

我们知道tableview的heightForRowAtIndexPath 会在 cellForRowAtIndexPath 方法之前执行,因此在计算cell高度的时候就不能通过表格的cell来计算,这样就导致动态计算高度变得有点困难。今天在网上找到下面的一种方法:

 

 

创建表格的cell

#pragma mark 表格-创建cell
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString* identifier = @"basis-cell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell==nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    NSInteger section = indexPath.section;
    
    NSInteger width = [Tool loadScreenSize].width;
    NSInteger height =100+50*section-10;
    
    UIView* view = [[UIView alloc]initWithFrame:CGRectMake(0+1, 0+1, width-2, height)];
    view.backgroundColor=[UIColor grayColor];
    
    UIButton* btn = [Tool createButton:CGRectMake(5, 5, 100, 40) withDelegate:self withAction:nil withTitle:@"button" withBgColor:[UIColor yellowColor]];
    [view addSubview:btn];
    
    [cell.contentView addSubview:view];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    
    
    [[heights_ objectAtIndex:indexPath.section] setObject:[NSString stringWithFormat:@"%f",view.frame.size.height] atIndex:indexPath.row];

    return cell;
}

 

 

 

表格高度设置,在方法heightForRowAtIndexPath重写中先调用下方法:UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath]; 先把表格的cell手动生成出来,然后获取其高度。

 

 

#pragma mark 表格-配置cell高度
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    UIView* view = [cell.contentView.subviews objectAtIndex:0];
    NSLog(@"cell.frame.size.height=%f",view.frame.size.height);
    return view.frame.size.height;
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值