动态调整UITableViewCell高度的实现方法

本文介绍了一种简单的方法来实现UITableViewCell的动态高度调整。通过在cellForRowAtIndexPath方法中根据内容计算UILabel的高度,并相应地调整UITableViewCell的高度,使得每个单元格能根据其内容自动适配高度。

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

转自:http://www.cocoachina.com/iphonedev/sdk/2011/0627/2983.html


有时我们需要动态调整UITableViewCell的高度,根据内容的不同设置不同的高度,以前看到一种实现方法,写得有点麻烦,具体地址找不到了,这里有个更好的(至少我认为),分享一下部分代码。


  1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {  
  2.       
  3.     static NSString *CellIdentifier = @"Cell";  
  4.       
  5.     UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];  
  6.     if (cell == nil) {  
  7.         cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];  
  8.         UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];  
  9.         label.tag = 1;  
  10.         label.lineBreakMode = UILineBreakModeWordWrap;  
  11.         label.highlightedTextColor = [UIColor whiteColor];  
  12.         label.numberOfLines = 0;  
  13.         label.opaque = NO; // 选中Opaque表示视图后面的任何内容都不应该绘制  
  14.         label.backgroundColor = [UIColor clearColor];  
  15.         [cell.contentView addSubview:label];  
  16.         [label release];  
  17.     }  
  18.       
  19.     UILabel *label = (UILabel *)[cell viewWithTag:1];  
  20.     NSString *text;  
  21.     text = [textArray objectAtIndex:indexPath.row];  
  22.     CGRect cellFrame = [cell frame];  
  23.     cellFrame.origin = CGPointMake(0, 0);  
  24.       
  25.     label.text = text;  
  26.     CGRect rect = CGRectInset(cellFrame, 2, 2);  
  27.     label.frame = rect;  
  28.     [label sizeToFit];  
  29.     if (label.frame.size.height > 46) {  
  30.         cellFrame.size.height = 50 + label.frame.size.height - 46;  
  31.     }  
  32.     else {  
  33.         cellFrame.size.height = 50;  
  34.     }  
  35.     [cell setFrame:cellFrame];  
  36.       
  37.     return cell;  
  38. }  
  39.   
  40. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  
  41. {  
  42.     UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];  
  43.     //UITableViewCell *cell = [self cellForRowAtIndexPath:indexPath];  
  44.     return cell.frame.size.height;  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值