动态计算UITableViewCell高度

UILabel in UITableViewCell

Auto Layout - UILabel的属性Lines设为了0表示显示多行。Auto Layout约束一定要建立完完整 - UITableView使用C1.xib中自定义的Cell,那么我们需要向UITableView进行注册

 UINib *cellNib = [UINib nibWithNibName:@"C1" bundle:nil];
[self.tableView registerNib:cellNib forCellReuseIdentifier:@"C1"];
  • 数据源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return self.tableData.count; }
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
C1 *cell = [self.tableView dequeueReusableCellWithIdentifier:@"C1"];
cell.t.text = [self.tableData objectAtIndex:indexPath.row]; return cell;
}
  • 需要用到一个新的API systemLayoutSizeFittingSize:来计算UITableViewCell所占空间高度。Cell的高度是在- (CGFloat)tableView:(UITableView )tableView heightForRowAtIndexPath:(NSIndexPath )indexPath这个UITableViewDelegate的方法里面传给UITableView的。
  • 这里有一个需要特别注意的问题,也就是效率问题。UITableView是一次性计算完所有Cell的高度,如果有1W个Cell,那么- (CGFloat)tableView:(UITableView )tableView heightForRowAtIndexPath:(NSIndexPath )indexPath就会触发1W次,然后才显示内容。不过在iOS7以后,提供了一个新方法可以避免这1W次调用,它就是- (CGFloat)tableView:(UITableView )tableView estimatedHeightForRowAtIndexPath:(NSIndexPath )indexPath。要求返回一个Cell的估计值,实现了这个方法,那只有显示的Cell才会触发计算高度的protocol. 由于systemLayoutSizeFittingSize需要cell的一个实例才能计算,所以这儿用一个成员变量存一个Cell的实列,这样就不需要每次计算Cell高度的时候去动态生成一个Cell实例,这样即方便也高效也少用内存,可谓一举三得。
  • 声明一个存计算Cell高度的实例变量
 @property (nonatomic, strong) UITableViewCell *prototypeCell;
  • 初始化prototypeCell
self.prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:@"C1"];
  • 计算Cell高度的实现
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
C1 *cell = (C1 *)self.prototypeCell;
cell.t.text = [self.tableData objectAtIndex:indexPath.row];
CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
NSLog(@"h=%f", size.height + 1); return 1 + size.height;
}
  • UITableViewCell的高度要比它的contentView要高1,也就是它的分隔线的高度

Manual Layout

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
C3 *cell = [self.tableView dequeueReusableCellWithIdentifier:@"C3"];
cell.t.text = [self.tableData objectAtIndex:indexPath.row];
[cell.t sizeToFit]; return cell; }
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
C3 *cell = (C3 *)self.prototypeCell;
NSString *str = [self.tableData objectAtIndex:indexPath.row];
cell.t.text = str;
CGSize s = [str calculateSize:CGSizeMake(cell.t.frame.size.width, FLT_MAX) font:cell.t.font];
CGFloat defaultHeight = cell.contentView.frame.size.height;
CGFloat height = s.height > defaultHeight ? s.height : defaultHeight;
NSLog(@"h=%f", height);
return 1 + height; }
// NSString的类别
- (CGSize)calculateSize:(CGSize)size font:(UIFont *)font {
CGSize expectedLabelSize = CGSizeZero;
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
NSDictionary *attributes = @{NSFontAttributeName:font, NSParagraphStyleAttributeName:paragraphStyle.copy};
expectedLabelSize = [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes context:nil].size; } else { expectedLabelSize = [self sizeWithFont:font constrainedToSize:size lineBreakMode:NSLineBreakByWordWrapping]; }
return CGSizeMake(ceil(expectedLabelSize.width), ceil(expectedLabelSize.height));
}

UITextView in UITableViewCell

Auto Layout - 计算高度的代码

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
C2 *cell = (C2 *)self.prototypeCell;
cell.t.text = [self.tableData objectAtIndex:indexPath.row];
CGSize size = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
CGSize textViewSize = [cell.t sizeThatFits:CGSizeMake(cell.t.frame.size.width, FLT_MAX)];
CGFloat h = size.height + textViewSize.height; h = h > 89 ? h : 89; //89是图片显示的最低高度, 见xib
NSLog(@"h=%f", h);
return 1 + h; }

说明:通过sizeThatFits:计算的UITextView的高度(这是计算UITextView内容全部显示时的方法),然后加上systemLayoutSizeFittingSize:返回的高度。为什么要这样呢? 因为UITextView内容的高度不会影响systemLayoutSizeFittingSize计算。 > 此图中距顶的约束是10, 距底的约束8, 距左边约束是87,距右边的约束是13, 那么systemLayoutSizeFittingSize:返回的CGSize为height等于19, size等于100. 它UITextView的frame是不影响systemLayoutSizeFittingSize:的计算。所以,需要加上textViewSize.height

Manual Layout

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
C4 *cell = [self.tableView dequeueReusableCellWithIdentifier:@"C4"];
cell.t.text = [self.tableData objectAtIndex:indexPath.row];
[cell.t sizeToFit];
return cell; }
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
C4 *cell = (C4 *)self.prototypeCell;
NSString *str = [self.tableData objectAtIndex:indexPath.row];
cell.t.text = str;
CGSize s = [cell.t sizeThatFits:CGSizeMake(cell.t.frame.size.width, FLT_MAX)];
CGFloat defaultHeight = cell.contentView.frame.size.height;
CGFloat height = s.height > defaultHeight ? s.height : defaultHeight;
return 1 + height; }

动态计算UITableViewCell高度的更多相关文章

  1. 转:动态计算UITableViewCell高度详解

    转自:http://www.cocoachina.com/industry/20140604/8668.html   不知道大家有没有发现,在iOS APP开发过程中,UITableView是我们显示 ...

  2. 动态计算UITableViewCell高度详解 (转)

    感觉挺有用的一篇文章,分析了4种解决方案.回头测试之.如果有别的方案,我会在后面补上. 原文地址:http://www.ifun.cc/blog/2014/02/21/dong-tai-ji-suan ...

  3. 动态计算UITableViewCell高度详解

    本文将介绍四种情况下UITableViewCell的计算方式,分别是: Auto Layout with UILabel in UITableViewCell Auto Layout with UIT ...

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

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPa ...

  5. 动态计算Label高度

    //1.设置该label的numberOfLines为0 self.titleLabel.numberOfLines = 0;    //2.字体的设置要与之前相同 NSDictionary * at ...

  6. 根据文字动态计算Label高度或宽度

    //根据已知的label宽度计算文字高度 CGRect rect = [reson boundingRectWithSize:CGSizeMake(label_W, 0) options:NSStri ...

  7. swift - 动态计算文本高度

        func heightOfCell(text : String) -> CGFloat {        let attributes = [NSFontAttributeName:UI ...

  8. iOS学习之根据文本内容动态计算文本框高度的步骤

    在视图加载的过程中,是先计算出frame,再根据frame加载视图的,所以在设计计算高度的方法的时候,设计成加号方法; //首先给外界提供计算cell高度的方法 + (CGFloat)heightFo ...

  9. UITableViewCell 高度自适应

    UITableViewCell 高度自适应一直是我们做动态Cell高度时遇到的最烦躁的问题,Cell动态高度计算可以去看看sunny的这篇文章介绍,今天主要和大家分享下我在使用systemLayout ...

随机推荐

  1. SharePoint 2013 托管导航 无法被开启的解决办法

    在阅读了园子中霖雨的一片博文<SharePoint 2013 托管导航及相关配置>之后,非常想尝试一下SharePoint 2013 中的这个新功能,但是我的网站集包括样式是从2010升级 ...

  2. Oracle 10g安全加固(审计、监听密码)

    环境: Linux 6.4 + Oracle 10.2.0.4 1. Oracle 10g 审计功能 2. 对数据库监听器的关闭和启动设置密码 1. Oracle 10g 审计功能 Oracle 10 ...

  3. ssh整合问题总结--在添加商品模块实现图片(文件)的上传

    今天在做毕设(基于SSH的网上商城项目)中碰到了一个文件上传的需求,就是在后台管理员的商品模块中,有一个添加商品,需要将磁盘上的图片上传到tomcat保存图片的指定目录中: 完成这个功能需要两个步,第 ...

  4. hibernate笔记--实体类映射文件"*.hbm.xml"详解

    实体类就是指普通的POJO,Hibernate并不知道那个实体类对应数据库的哪一张表,所以还需要配置一下,常用的方式就是*.hbm.xml文件[配置与@注解配置,这里介绍前者的详细属性: <?x ...

  5. Struts2学习笔记--使用Response下载文件和Struts2的StreamResult文件下载

    使用Response下载文件,servlet中的文件下载是通过流来实现的   我在webRoot文件夹下新建了一个文件夹from,里边放了一张图片,这里就以下载这张图片为例:download.jsp很 ...

  6. HTML5 Canvas 画布

    一.Canvas是什么? canvas,是一个画布,canvas元素用于在网页上绘制图形. canvas 拥有多种绘制路径.矩形.圆形.字符以及添加图像的方法. 二.创建Canvas元素 加上基本的属 ...

  7. spring boot 添加拦截器

    构建一个spring boot项目. 添加拦截器需要添加一个configuration @Configuration @ComponentScan(basePackageClasses = Appli ...

  8. Spring-Boot - 初步搭建

    official document:http://projects.spring.io/spring-boot/ 项目代码: https://github.com/chenxing12/springb ...

  9. Windows Phone 的 TextBox 的实现 PropertyChanged

    比如,View 的文本框 TextBox1 绑定了 ViewModel 的 Msg 属性, 当想把文本框输入的内容输入过程中实时更新到绑定的 Msg ,在Windows Phone 中是无法通过设置  ...

  10. UIAlertController 部分用法及属性

    //创建UIAlertController:初始化UIAlertController 需要使用alertControllerWithTitle UIAlertController *alertCont ...