UITableViewCell 高度自适应
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. 建一个继承于UITableViewController
的ZHCustomLayoutTableViewController
建一个在函数
-(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];
- CGFloat contentViewWidth = CGRectGetWidth(self.tableView.bounds);
Demo 下载地址
UITableViewCell 高度自适应的更多相关文章
- uitableviewcell高度自适应笔记
今天看了几篇uitableviewcell高度自适应的文章,大体分为两种方式. 第一种方式,cell里面有label,在cellforrow绘制的时候计算Label的可能高度,并且在此时重新计算cel ...
- UITableViewCell高度自适应探索--AutoLayout结合Frame
UITableViewCell高度自适应探索--UITableView+FDTemplateLayoutCell地址: http://www.jianshu.com/p/7839e3a273a6UIT ...
- UITableViewCell高度自适应的关键点
iOS开发中对于UITableViewCell高度自适应的文章已经很多很多,但如果cell内容比较复杂,刚使用autolayout配置自使用时还是总不能一次性成功. KEY POINT 这里只说设置的 ...
- 原生的UITableViewCell高度自适应,textLabel自动换行显示
/* * 设置子项cell **/ - (UITableViewCell *)getChildCell:(UITableView *)tableView and:(NSIndexPath *)inde ...
- 第二篇、为UITableViewCell 高度自适应加速 缓存cell的高度
通过NSCache缓存已经算好的行高 @interface ZHCellHeightCalculator : NSObject //系统计算高度后缓存进cache -(void)setHeight:( ...
- UITableViewCell 高度计算从混沌初始到天地交泰
[原创]UITableViewCell 高度计算从混沌初始到天地交泰 本文主要基予iOS UITableViewCell 高度自适应计算问题展开陈述,废话少说直入正题: UITableView控件可能 ...
- autolayout 高度自适应
https://lvwenhan.com/ios/449.html #import "ViewController.h" #import "MyTableViewCell ...
- 关于TableViewCell高度自适应问题的整理
TableViewCell高度自适应在网上有很多资料,我只想找出最最最简单的一种方法. 首先梳理一下思路.说到TableViewCell我们第一个想到的问题或许就是cell的复用问题. 1. [se ...
- SnapKit swift实现高度自适应的新浪微博布局
SnapKit swift版的自动布局框架,第一次使用感觉还不错. SnapKit是一个优秀的第三方自适应布局库,它可以让iOS.OS X应用更简单地实现自动布局(Auto Layout).GtiHu ...
随机推荐
- 手机web开发
jqmobi 可以代理 jquery mobile,似乎更加小和快 http://app-framework-software.intel.com/components.php bootstrap ...
- java高并发,如何解决,什么方式解决
之前我将高并发的解决方法误认为是线程或者是队列可以解决,因为高并发的时候是有很多用户在访问,导致出现系统数据不正确.丢失数据现象,所以想到 的是用队列解决,其实队列解决的方式也可以处理,比如我们在竞拍 ...
- 【转】读取android根目录下的文件或文件夹
原文网址:http://my.oschina.net/Ccx371161810/blog/287823 读取android根目录下的文件或文件夹 SDK的操作 读取android根目录下的文件或文件夹 ...
- iOS--跳转到APPstore评分
本代码适用于iOS7之后的版本: NSString *str = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/ ...
- 随心所欲的DateTime显示格式
任何项目,难免会碰到DateTime的显示问题,.net框架虽提供丰富多样的显示方法,但我很少使用,因老忘记细节,每次都要纠结到底月份在前还是年份在前:日期分隔符到底是“/”,还是“\”,还是“-”等 ...
- Codeforces 628E Zbazi in Zeydabad 树状数组
题意:一个n*m的矩阵,要么是 . 要么是 z ,问可以形成几个大z 分析:(直接奉上官方题解,我感觉说的实在是太好了) Let's precalculate the values zlij, zri ...
- 《UNIX环境高级编程 第2版》读书笔记
CH1-2:基础知识.标准化 1 文件和目录 文件名:不能含/(分隔路径)和null(终止路径),255字符. 目录处理:opendir() readdir() closedir() 更改工作目录:c ...
- zabbix监控域名带宽
代码地址:https://github.com/Ma-Jing/python/blob/master/ngxv2_traffic_daemon.py READ.md里有使用说明! #!/usr/bin ...
- Python Paste.deploy 笔记
首先python paste是一个WSGI工具包,在WSGI的基础上包装了几层,让应用管理和实现变得方便.说实话,Python Paste的文档做的真差劲!加之python代码可读性本来就不怎么滴,真 ...
- 【VMware虚拟机】【克隆问题】在VMware 9.0下克隆CentOS6.5虚拟机无法识别eth网卡
[日期]2014年4月23日 [平台]windows 8 vmware workstation 9.0 centos 6.5 [日志]1)执行ifconfig命令,输出: 2)查看/etc/udev/ ...