iOS动态改变TableView Cell高度

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;
}

猜你喜欢

转载自stephen830.iteye.com/blog/2243037