当前位置: 首页 > news >正文

UITableViewCell 高度自适应

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

Demo gif

1.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的布局如下所示:

2926059-4331432160e72e50.png

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

相关文章:

  • 技术及培训问题讨论专贴。[学员必看]
  • ADSL Modem之DHCP的配置及应用
  • BI_DBA_安装(1):安装OS及DB
  • 洛谷P1582 倒水
  • ISA 2004 進階管理實務
  • PHP系列目录
  • 怎样成为优秀的软件测试员
  • 无法创建链接服务器 xxx 的 OLE DB 访问接口 OraOLEDB.Oracle 的实例。 (Microsoft SQL Server,错误: 7302)...
  • 使用Java操作文本文件的方法详解
  • 随笔
  • Redis集群搭建与简单使用
  • 自动压缩MS SQL数据库日志
  • 五大绝招让你永远是人才
  • [转载]什么是IOC
  • 洛谷P3146 [USACO16OPEN]248
  • C学习-枚举(九)
  • exif信息对照
  • gf框架之分页模块(五) - 自定义分页
  • js
  • JS创建对象模式及其对象原型链探究(一):Object模式
  • Mac 鼠须管 Rime 输入法 安装五笔输入法 教程
  • PAT A1050
  • session共享问题解决方案
  • VirtualBox 安装过程中出现 Running VMs found 错误的解决过程
  • 程序员最讨厌的9句话,你可有补充?
  • 浮动相关
  • 基于Vue2全家桶的移动端AppDEMO实现
  • 解决iview多表头动态更改列元素发生的错误
  • 理清楚Vue的结构
  • 前端 CSS : 5# 纯 CSS 实现24小时超市
  • 浅谈web中前端模板引擎的使用
  • 如何进阶一名有竞争力的程序员?
  • 实战|智能家居行业移动应用性能分析
  • 思考 CSS 架构
  • 一些css基础学习笔记
  • Linux权限管理(week1_day5)--技术流ken
  • #《AI中文版》V3 第 1 章 概述
  • #Z2294. 打印树的直径
  • #考研#计算机文化知识1(局域网及网络互联)
  • $.extend({},旧的,新的);合并对象,后面的覆盖前面的
  • (13)Latex:基于ΤΕΧ的自动排版系统——写论文必备
  • (bean配置类的注解开发)学习Spring的第十三天
  • (附源码)springboot课程在线考试系统 毕业设计 655127
  • (附源码)ssm基于jsp高校选课系统 毕业设计 291627
  • (力扣题库)跳跃游戏II(c++)
  • (利用IDEA+Maven)定制属于自己的jar包
  • (生成器)yield与(迭代器)generator
  • (完整代码)R语言中利用SVM-RFE机器学习算法筛选关键因子
  • (原創) 如何優化ThinkPad X61開機速度? (NB) (ThinkPad) (X61) (OS) (Windows)
  • (转)Android学习系列(31)--App自动化之使用Ant编译项目多渠道打包
  • (转)如何上传第三方jar包至Maven私服让maven项目可以使用第三方jar包
  • .helper勒索病毒的最新威胁:如何恢复您的数据?
  • .NET CLR Hosting 简介
  • .net 程序发生了一个不可捕获的异常
  • .Net6使用WebSocket与前端进行通信