动态计算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. 在Objective-C中浅谈面向对象

    接触面向对象也有一段时间了,当时是通过C++学习的OOP,后来又接触到了PHP和Java.每种OOP的语言在面向对象上或多或少都会有不同的地方,现在在学习OC的面向对象部分,又感觉到OC面向对象的特点 ...

  2. 如何远程备份MySQL binlog

    以前备份binlog时,都是先在本地进行备份压缩,然后发送到远程服务器中.但是这其中还是有一定风险的,因为日志的备份都是周期性的,如果在某个周期中,服务器宕机了,硬盘损坏了,就可能导致这段时间的bin ...

  3. JDBC常用API小结

    建立数据库链接的三种方式: package com.victor_01; import java.sql.Connection; import java.sql.Driver; import java ...

  4. 1Z0-053 争议题目解析46

    1Z0-053 争议题目解析46 考试科目:1Z0-053 题库版本:V13.02 题库中原题为: 46.What happens when you run the SQL Tuning Adviso ...

  5. Date, TimeZone, MongoDB, java中date的时区问题

    打印new Date(),Fri Aug 12 13:37:51 CST 2016. 显示Asia/Shanghai的时区,但是date toString 的时区简写却是CST.更坑爹的是,Googl ...

  6. 小白Linux入门 二

    参考: http://edu.51cto.com/lesson/id-11222.html CPU中有计算单元 控制单元.它通过桥接芯片与存储器进行匹配 其中北桥是高速 南桥是低速 包括IDE USB ...

  7. 我的angularjs源码学习之旅1——初识angularjs

    angular诞生有好几年光景了,有Google公司的支持版本更新还是比较快,从一开始就是一个热门技术,但是本人近期才开始接触到.只能感慨自己学习起点有点晚了.只能是加倍努力赶上技术前线. 因为有分析 ...

  8. 【非原创】IOS 验证文字是否是中文

    从环信中找到的部分不错的代码,拿出来记录一下 是否是中文 -(BOOL)isChinese{ NSString *match=@"(^[\u4e00-\u9fa5]+$)"; NS ...

  9. HtmlHelper拓展实现RadioList

    mvc中HtmlHelper可以帮助我们生成许多Html控件,但是没有类似DropDownList的RadioList,但是发现这些方法都是拓展方法,于是就想自己也拓展一个RadioList 从网上下 ...

  10. js用户管理中心tab切换界面模板

    效果体验:http://hovertree.com/texiao/js/27/ 效果图如下: 代码如下: <!DOCTYPE html> <html> <head> ...