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;
}
本文介绍了一种在 iOS 开发中动态调整 TableViewCell 高度的方法。该方法通过预先创建 cell 并获取其内容视图的高度来确定 cell 的高度。
8440

被折叠的 条评论
为什么被折叠?



