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

Demo gif

先看原函数注释

  1. /* The size fitting most closely to targetSize in which the receiver's subtree can be laid out while optimally satisfying the constraints. If you want the smallest possible size, pass UILayoutFittingCompressedSize; for the largest possible size, pass UILayoutFittingExpandedSize.
  2.  Also see the comment for UILayoutPriorityFittingSizeLevel.
  3.  */- (CGSize)systemLayoutSizeFittingSize:(CGSize)targetSize NS_AVAILABLE_IOS(6_0); // Equivalent to sending -systemLayoutSizeFittingSize:withHorizontalFittingPriority:verticalFittingPriority: with UILayoutPriorityFittingSizeLevel for both priorities.

从注释中我们可以看出,当你的约束条件配置好后它可以计算出最接近目标的Size,那我们该如何下手呢?

1.首先我们需要建一个UITableViewCell

假如我们Cell的布局如下所示:

Cell所对应的Class我们取名为ZHCalculateTableViewCell
所带属性我们定义为:

  1. @interface ZHCalculateTableViewCell : UITableViewCell
  2. @property (weak, nonatomic) IBOutlet UILabel *TitleLabel;
  3. @property (weak, nonatomic) IBOutlet UILabel *ContentLabel;
  4. @property (weak, nonatomic) IBOutlet UIImageView *showImgView;
  5. @property (weak, nonatomic) IBOutlet UILabel *UseNameLabel;
  6. @property (weak, nonatomic) IBOutlet UILabel *TimeLabel;
  7. @property (strong, nonatomic) ZHCalculateHeightModel *model;
  8. @end

看到这里也许你会疑惑ZHCalculateHeightModel是什么,它是我们Cell所要展示的数据来源!

2.然后我们为我们的Cell建个数据模型

Cell的模型名称我们暂定为:ZHCalculateHeightModel
所带属性:

  1. @interface ZHCalculateHeightModel : NSObject
  2. @property (nonatomic, strong) NSString *title;
  3. @property (nonatomic, strong) NSString *content;
  4. @property (nonatomic, strong) NSString *username;
  5. @property (nonatomic, strong) NSString *time;
  6. @property (nonatomic, strong) NSString *imageName;

Ok,数据模型建立好了,展示的TableViewCell也有了, Just Show it~

3. 建一个继承于UITableViewControllerZHCustomLayoutTableViewController

  • 建一个在函数-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath中调用的Cell:

    1. @property (nonatomic, strong)  ZHCalculateTableViewCell *prototypeCell;
  • 注册Cell

  1. [self.tableView registerNib:[UINib nibWithNibName:@"ZHCalculateTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:CellIdentifier];
  2. self.tableView.estimatedRowHeight = 100;//很重要保障滑动流畅性
  3. self.prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  • 动态计算高度

  1.    -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  2. {
  3.  
  4.     ZHCalculateTableViewCell *cell = self.prototypeCell;
  5.     cell.contentView.translatesAutoresizingMaskIntoConstraints = NO;
  6.     [self configureCell:cell atIndexPath:indexPath];//必须先对Cell中的数据进行配置使动态计算时能够知道根据Cell内容计算出合适的高度
  7.  
  8.     /*------------------------------重点这里必须加上contentView的宽度约束不然计算出来的高度不准确-------------------------------------*/
  9.     CGFloat contentViewWidth = CGRectGetWidth(self.tableView.bounds);
  10.     NSLayoutConstraint *widthFenceConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:contentViewWidth];
  11.     [cell.contentView addConstraint:widthFenceConstraint];
  12.     // Auto layout engine does its math
  13.     CGFloat fittingHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
  14.     [cell.contentView removeConstraint:widthFenceConstraint];
  15.     /*-------------------------------End------------------------------------*/
  16.  
  17.     return fittingHeight+2*1/[UIScreen mainScreen].scale;//必须加上上下分割线的高度
  18. }
  19.  
  20. #pragma mark Configure Cell Data
  21. - (void)configureCell:(ZHCalculateTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
  22.     cell.model = [dataArray objectAtIndex:indexPath.row];//Cell中对其进行处理
  23. }

ZHCalculateTableViewCell Model的Set函数重写为

  1. #pragma mark - Setters
  2. -(void)setModel:(ZHCalculateHeightModel *)model
  3. {
  4.     _model = model;
  5.     self.TitleLabel.text = model.title;
  6.     self.ContentLabel.text = model.content;
  7.     self.showImgView.image = model.imageName.length > 0 ? [UIImage imageNamed:model.imageName] : nil;
  8.     self.UseNameLabel.text = model.username;
  9.     self.TimeLabel.text = model.time;
  10.  
  11. }

扩展

我们可以在计算高度后对其进行缓存,下次可以直接返回!

总结

  • -(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath一定不要用ZHCalculateTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];来获取Cell。

  • 上述动态计算Cell高度中最最重要的是需要在计算前先初始化Cell中的数据。

  • 一定要对ContentView加上宽度约束。

    1. CGFloat contentViewWidth = CGRectGetWidth(self.tableView.bounds);
    2.   NSLayoutConstraint *widthFenceConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:contentViewWidth];
    3.   [cell.contentView addConstraint:widthFenceConstraint];
    4.   // Auto layout engine does its math
    5.   CGFloat fittingHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
    6.   [cell.contentView removeConstraint:widthFenceConstraint];

Demo 下载地址

GitHub

UITableViewCell 高度自适应的更多相关文章

  1. uitableviewcell高度自适应笔记

    今天看了几篇uitableviewcell高度自适应的文章,大体分为两种方式. 第一种方式,cell里面有label,在cellforrow绘制的时候计算Label的可能高度,并且在此时重新计算cel ...

  2. UITableViewCell高度自适应探索--AutoLayout结合Frame

    UITableViewCell高度自适应探索--UITableView+FDTemplateLayoutCell地址: http://www.jianshu.com/p/7839e3a273a6UIT ...

  3. UITableViewCell高度自适应的关键点

    iOS开发中对于UITableViewCell高度自适应的文章已经很多很多,但如果cell内容比较复杂,刚使用autolayout配置自使用时还是总不能一次性成功. KEY POINT 这里只说设置的 ...

  4. 原生的UITableViewCell高度自适应,textLabel自动换行显示

    /* * 设置子项cell **/ - (UITableViewCell *)getChildCell:(UITableView *)tableView and:(NSIndexPath *)inde ...

  5. 第二篇、为UITableViewCell 高度自适应加速 缓存cell的高度

    通过NSCache缓存已经算好的行高 @interface ZHCellHeightCalculator : NSObject //系统计算高度后缓存进cache -(void)setHeight:( ...

  6. UITableViewCell 高度计算从混沌初始到天地交泰

    [原创]UITableViewCell 高度计算从混沌初始到天地交泰 本文主要基予iOS UITableViewCell 高度自适应计算问题展开陈述,废话少说直入正题: UITableView控件可能 ...

  7. autolayout 高度自适应

    https://lvwenhan.com/ios/449.html #import "ViewController.h" #import "MyTableViewCell ...

  8. 关于TableViewCell高度自适应问题的整理

    TableViewCell高度自适应在网上有很多资料,我只想找出最最最简单的一种方法. 首先梳理一下思路.说到TableViewCell我们第一个想到的问题或许就是cell的复用问题. 1.  [se ...

  9. SnapKit swift实现高度自适应的新浪微博布局

    SnapKit swift版的自动布局框架,第一次使用感觉还不错. SnapKit是一个优秀的第三方自适应布局库,它可以让iOS.OS X应用更简单地实现自动布局(Auto Layout).GtiHu ...

随机推荐

  1. 手机web开发

    jqmobi 可以代理 jquery mobile,似乎更加小和快 http://app-framework-software.intel.com/components.php   bootstrap ...

  2. java高并发,如何解决,什么方式解决

    之前我将高并发的解决方法误认为是线程或者是队列可以解决,因为高并发的时候是有很多用户在访问,导致出现系统数据不正确.丢失数据现象,所以想到 的是用队列解决,其实队列解决的方式也可以处理,比如我们在竞拍 ...

  3. 【转】读取android根目录下的文件或文件夹

    原文网址:http://my.oschina.net/Ccx371161810/blog/287823 读取android根目录下的文件或文件夹 SDK的操作 读取android根目录下的文件或文件夹 ...

  4. iOS--跳转到APPstore评分

    本代码适用于iOS7之后的版本: NSString *str = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/ ...

  5. 随心所欲的DateTime显示格式

    任何项目,难免会碰到DateTime的显示问题,.net框架虽提供丰富多样的显示方法,但我很少使用,因老忘记细节,每次都要纠结到底月份在前还是年份在前:日期分隔符到底是“/”,还是“\”,还是“-”等 ...

  6. Codeforces 628E Zbazi in Zeydabad 树状数组

    题意:一个n*m的矩阵,要么是 . 要么是 z ,问可以形成几个大z 分析:(直接奉上官方题解,我感觉说的实在是太好了) Let's precalculate the values zlij, zri ...

  7. 《UNIX环境高级编程 第2版》读书笔记

    CH1-2:基础知识.标准化 1 文件和目录 文件名:不能含/(分隔路径)和null(终止路径),255字符. 目录处理:opendir() readdir() closedir() 更改工作目录:c ...

  8. zabbix监控域名带宽

    代码地址:https://github.com/Ma-Jing/python/blob/master/ngxv2_traffic_daemon.py READ.md里有使用说明! #!/usr/bin ...

  9. Python Paste.deploy 笔记

    首先python paste是一个WSGI工具包,在WSGI的基础上包装了几层,让应用管理和实现变得方便.说实话,Python Paste的文档做的真差劲!加之python代码可读性本来就不怎么滴,真 ...

  10. 【VMware虚拟机】【克隆问题】在VMware 9.0下克隆CentOS6.5虚拟机无法识别eth网卡

    [日期]2014年4月23日 [平台]windows 8 vmware workstation 9.0 centos 6.5 [日志]1)执行ifconfig命令,输出: 2)查看/etc/udev/ ...