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

Demo gif

先看原函数注释

/* 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.
 Also see the comment for UILayoutPriorityFittingSizeLevel.
 */- (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
所带属性我们定义为:

@interface ZHCalculateTableViewCell : UITableViewCell
@property (weak, nonatomic) IBOutlet UILabel *TitleLabel;
@property (weak, nonatomic) IBOutlet UILabel *ContentLabel;
@property (weak, nonatomic) IBOutlet UIImageView *showImgView;
@property (weak, nonatomic) IBOutlet UILabel *UseNameLabel;
@property (weak, nonatomic) IBOutlet UILabel *TimeLabel;
@property (strong, nonatomic) ZHCalculateHeightModel *model;
@end

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

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

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

@interface ZHCalculateHeightModel : NSObject
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *content;
@property (nonatomic, strong) NSString *username;
@property (nonatomic, strong) NSString *time;
@property (nonatomic, strong) NSString *imageName;

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

3. 建一个继承于UITableViewControllerZHCustomLayoutTableViewController

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

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

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

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

ZHCalculateTableViewCell Model的Set函数重写为

#pragma mark - Setters
-(void)setModel:(ZHCalculateHeightModel *)model
{
    _model = model;
    self.TitleLabel.text = model.title;
    self.ContentLabel.text = model.content;
    self.showImgView.image = model.imageName.length > 0 ? [UIImage imageNamed:model.imageName] : nil;
    self.UseNameLabel.text = model.username;
    self.TimeLabel.text = model.time; }

扩展

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

总结

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

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

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

    CGFloat contentViewWidth = CGRectGetWidth(self.tableView.bounds);
      NSLayoutConstraint *widthFenceConstraint = [NSLayoutConstraint constraintWithItem:cell.contentView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:1.0 constant:contentViewWidth];
      [cell.contentView addConstraint:widthFenceConstraint];
      // Auto layout engine does its math
      CGFloat fittingHeight = [cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize].height;
      [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. vfp 操作excel

    VFP全面控制EXCEL 收藏 VFP和Excel都可以用来进行处理数据库表格,如果巧妙地将二者的优点结合起来,将会大大方便我们的工作.比如我们可以利用VFP进行处理数据,而利用Excel的预览打印功 ...

  2. 【highcharts】

    zoomType positioner

  3. Spring编程风格

    给自己使用的无需定义接口:即一个模块内部的都是封装的,定义接口并不会得到很多好处,变过几次实现?? “优先面向接口编程,而非实现” 不是必须,是优先: 给朋友(第三方)使用的定义接口:即要公开的功能, ...

  4. EF的表连接方法Include() - nlh774

    在EF中表连接常用的有Join()和Include(),两者都可以实现两张表的连接,但又有所不同. 例如有个唱片表Album(AlbumId,Name,CreateDate,GenreId),表中含外 ...

  5. CCR

    不用任何与创建线程.资源互斥有关系的API写多线程程序 这次的例子,是一个很简单的控制台,她将面对瞬间提交的百万的数据,而面不改色(CPU.内存非常平稳),队列中始终只保存最新的数据,每次只处理cpu ...

  6. 网站HTTP请求过程解析

    网站性能优化中首要的一条就是要减少HTTP请求,那么为要减少HTTP请求呢?其实有些HTTP分析工具可以帮我们了解当浏览器请求一个资源时大致需要经历的哪些过程: 1 域名解析(DNS Lookup): ...

  7. linux内核-红黑树

    //rbtree.h /*   Red Black Trees   (C) 1999  Andrea Arcangeli <andrea@suse.de>     This program ...

  8. 【Hadoop代码笔记】目录

    整理09年时候做的Hadoop的代码笔记. 开始. [Hadoop代码笔记]Hadoop作业提交之客户端作业提交 [Hadoop代码笔记]通过JobClient对Jobtracker的调用看详细了解H ...

  9. SecureCRT配置显示的字符集

  10. js为select添加option

    <select id="shi"> function loadInfo(){ var shengId=document.getElementById("she ...