UITableViewCell根据内容自动高度

来源:互联网 发布:java做场景设计的优点 编辑:程序博客网 时间:2024/05/17 07:53

先记着个属性吧,知道就行:uitableview有个属性值 separatorStyle 可用来去掉cell间的白线:

tableView.separatorStyle =UITableViewCellSeparatorStyleNone;   //总共有三个值,可以试下有空

转载自:http://aclyyx.iteye.com/blog/1634726

啰嗦几句:

 

这里主要是通过NSString的sizeWithFont:constrainedToSize:lineBreakMode:方法实现。
该方法用于计算显示完整内容所需要的最小尺寸。

下面是摘抄的说明

 

NSString的函数sizeWithFont:constrainedToSize:lineBreakMode:
API文档解释:若字符串以规定的约束条件进行描绘,则返回实际的大小。
用途:返回以指定字体进行描绘时,字符串所占据的实际大小。
 

运行效果:


程序解析:

 

该部分主要摘抄自《UITableView高度自適應》,稍稍做了改动。

 

C代码  收藏代码
  1. - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath  
  2. {  
  3.     static NSString * CellIdentifier = @"MessageViewControllerCell";  
  4.   
  5.     int row = [indexPath row];  
  6.     UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];  
  7.   
  8.     if (cell == nil) {  
  9.         // 用何種字體進行顯示  
  10.         UIFont *font = [UIFont systemFontOfSize:14];  
  11.         // 該行要顯示的內容  
  12.         NSString *content = [_arr objectAtIndex:row];  
  13.         // 实例化单元格对象  
  14.         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];  
  15.         // 设置显示文字  
  16.         cell.textLabel.text = content;  
  17.         // 設置自動換行(重要)  
  18.         cell.textLabel.numberOfLines = 0;  
  19.         // 設置顯示字體(一定要和之前計算時使用字體一至)  
  20.         cell.textLabel.font = font;  
  21.     }  
  22.   
  23.     return cell;  
  24. }  

 

 

C代码  收藏代码
  1. - (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath  
  2. {  
  3.     int row = [indexPath row];  
  4.     // 列寬  
  5.     CGFloat contentWidth = self.tv.frame.size.width;  
  6.     // 用何種字體進行顯示  
  7.     UIFont *font = [UIFont systemFontOfSize:14];  
  8.     // 該行要顯示的內容  
  9.     NSString *content = [_arr objectAtIndex:row];  
  10.     // 計算出顯示完內容需要的最小尺寸  
  11.     CGSize size = [content sizeWithFont:font constrainedToSize:CGSizeMake(contentWidth, 1000.0f) lineBreakMode:UILineBreakModeWordWrap];  
  12.     // 這裏返回需要的高度  
  13.     return size.height+20;  
  14. }  

 

参考链接:

 

IOS开发之常用系统函数收集:http://fulerbakesi.iteye.com/blog/1592224
UITableView高度自適應:http://mrjeye.iteye.com/blog/1045785


原创粉丝点击