UITableView的cell 动态 定义 高度

转自 http://blog.youkuaiyun.com/jinglijun/article/details/8333827

首先在

UITableView 的代理方法中算出每个cell 的真实高度,然后设置便ok。如下:

  1. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{  
  2.     UITableViewCell *cell;  
  3.      if (indexPath.section==1) {  
  4.    
  5.       
  6.         UITableViewCell *newsCell = [DataTable dequeueReusableCellWithIdentifier:@"newsCell1"];  
  7.         if (newsCell==nil) {  
  8.             newsCell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle  
  9.                                               reuseIdentifier:@"newsCell1"]autorelease];  
  10.         }  
  11.         CGRect cellFrame = [newsCell frame]; //定义的cell 的 frame  
  12.     cellFrame.origin = CGPointMake(0,0);  
  13.           
  14.         UILabel *productLabel31=(UILabel *)[newsCell.contentView viewWithTag:111143];  
  15.         if (!productLabel31) {  
  16.             productLabel31=[[UILabel alloc]initWithFrame:CGRectMake(cellXOffset,6,sectionTwoLabelWidth,10)];  
  17.             productLabel31.backgroundColor=[UIColor clearColor];  
  18.             productLabel31.tag=111143;  
  19.             productLabel31.numberOfLines=0;  
  20.             productLabel31.lineBreakMode=UILineBreakModeWordWrap;  
  21.             productLabel31.text=[normalTitleArray objectAtIndex:indexPath.section];  
  22.             productLabel31.font= [UIFont systemFontOfSize:cellProductLabelFont];  
  23.               
  24.             CGSize size = [productLabel31.text sizeWithFont:[UIFont systemFontOfSize:cellProductLabelFont] constrainedToSize:CGSizeMake(sectionTwoLabelWidth, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap]; //算出cell 的具体高度  
  25.               
  26.             productLabel31.frame=CGRectMake(cellXOffset,6,sectionTwoLabelWidth,size.height);  
  27.             [newsCell.contentView addSubview:productLabel31];  
  28.             [productLabel31 release];  
  29.         }  
  30.         cell = newsCell;  
  31.         cellFrame.size.height = productLabel31.frame.origin.y+productLabel31.frame.size.height +2; // 改变cell 的frame  
  32.         [cell setFrame: cellFrame]; // 改变cell 的frame  
  33.           
  34.     }  
  35.     cell.selectionStyle=UITableViewCellSelectionStyleNone;  
  36.     return cell;  
  37. }  
  最后 还要在 UITableView 的代理方法heightForRowAtIndexPath中设置下cell 的高度:
  1. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{  
  2.        
  3.     UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];  
  4.    return cell.frame.size.height;  
  5. }  


 这样cell就可以伴随你cell 内容的多少而 任意改变高度了。 

效果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值