iOS之SelfSizing Cell-高度自动计算详细讲解

iOS8之后苹果为UITableView引入SelfSizing Cell,配合constraints的使用省去了动态计算Cell高度麻烦,而且有时还存在着计算不准确的尴尬😓。要想利用这个特性,Cell布局时必须要使用AutoLayout,无论是使用Interface Builder方式还是使用Coding方式,前提是必须能理解AutoLayout的布局思路和熟练使用Constraints。
TableView Cell能自己计算高度的原理其实是利用了AutoLayout中FittingSizing Control的原理, (可以参照我的另一篇文章《iOS开发之利用Autolayout做一个能WrapContent的自定义控件》
关于FittingSizing 布局的官方相关的描述如下:

Intrinsic Content Size Versus Fitting Size
The intrinsic content size acts as an input to Auto Layout. When a view has an intrinsic content size, the system generates constraints to represent that size and the constraints are used to calculate the layout.The fitting size, on the other hand, is an output from the Auto Layout engine.It is the size calculated for a view based on the view’s constraints. If the view lays out its subviews using Auto Layout,then the system may be able to calculate a fitting size for the view based on its content.The stack view is a good example. Barring any other constraints, the system calculates the stack view’s size based on its content and attributes. In many ways, the stack view acts as if it had an intrinsic content size: You can create a valid layout using only a single vertical and a single horizontal constraint to define its position. But its size is calculated by Auto Layout—it is not an input into Auto Layout. Setting the stack view’s CHCR priorities has no effect, because the stack view does not have an intrinsic content size.If you need to adjust the stack view’s fitting size relative to items outside the stack view, either create explicit constraints to capture those relationships or modify the CHCR priorities of the stack’s contents relative to the items outside the stack.

大体理解起来就是FittingSizing视图的大小是基于施加于视图的上的约束计算而来,如果这个视图是个容器视图,则它所包含的子视图的填充大小就会影响这个视图的布局大小,比如这里要讲的TableView Cell。假设Cell上放置了一个Label,这里单元格的高度其实就是Label显示文本的高度,利用Autolayout,Label本身是可以知道有多大,但是Cell并不知道,如何关联呢?It is the size calculated for a view based on the view’s constraints.
就是这样的,我们让Cell的top equals to the top of Label AND bottom equals to the bottom of Label,可以想象Cell是在垂直方向被Label撑开了。

示例代码如下

@implementation SelfSizingCell
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if(self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]){
        
        _contentLabel = [[UILabel alloc] initWithFrame:CGRectZero];
        _contentLabel.numberOfLines = 0;
        [self.contentView addSubview:_contentLabel];
        _contentLabel.translatesAutoresizingMaskIntoConstraints = NO;
        _contentLabel.preferredMaxLayoutWidth = CGRectGetWidth([UIScreen mainScreen].bounds)-30;
        
        [_contentLabel setContentHuggingPriority:751 forAxis:0];
        [_contentLabel setContentHuggingPriority:751 forAxis:1];
        
        [_contentLabel setContentCompressionResistancePriority:250 forAxis:0];
        [_contentLabel setContentCompressionResistancePriority:250 forAxis:1];
        
        
        NSArray *_constraints = @[[NSLayoutConstraint constraintWithItem:_contentLabel
                                                               attribute:NSLayoutAttributeLeft
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.contentView
                                                               attribute:NSLayoutAttributeLeft
                                                              multiplier:1
                                                                constant:15],
                                  [NSLayoutConstraint constraintWithItem:_contentLabel
                                                               attribute:NSLayoutAttributeRight
                                                               relatedBy:NSLayoutRelationLessThanOrEqual
                                                                  toItem:self.contentView
                                                               attribute:NSLayoutAttributeRight
                                                              multiplier:1
                                                                constant:-15],
                                  [NSLayoutConstraint constraintWithItem:_contentLabel
                                                               attribute:NSLayoutAttributeTop
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.contentView
                                                               attribute:NSLayoutAttributeTop
                                                              multiplier:1
                                                                constant:10],
                                  [NSLayoutConstraint constraintWithItem:_contentLabel
                                                               attribute:NSLayoutAttributeBottom
                                                               relatedBy:NSLayoutRelationEqual
                                                                  toItem:self.contentView
                                                               attribute:NSLayoutAttributeBottom
                                                              multiplier:1
                                                                constant:-10]];
        [NSLayoutConstraint activateConstraints:_constraints];
    }
    return self;
}
@end

我们做Cell布局时一般将自定义控件放在ContentView上,所以施加的约束也是相对于ContentView,这个一定不能错!ContentView和Cell之间本身也是存在约束的,不需要我们考虑的。至于使用Masonry的代码会更简单、简洁,这里不贴代码了,而使用Interface builder添加约束的,不是很喜欢也不多做解释。
到这里几乎完成了这项工作的80%了,剩下的就是UITableView的属性配置了,即如下代码

tableView.estimatedRowHeight = 44.0
tableView.rowHeight = UITableViewAutomaticDimension

estimatedRowHeight:默认值UITableViewAutomaticDimension。设置一个非负的值可以提高TableView的加载效率,提升体验性,而设置值为零则禁掉了预估高度的功能。如果要使用SelfSizing Cell是需要设置estimatedRowHeight属性的。
rowHeight:默认值UITableViewAutomaticDimension。如果是Coding的话,其实是不需要显示设置这个属性,只有用Interface Builder创建的Cell需要显示设置tableView.rowHeight = UITableViewAutomaticDimension

详细的描述可以参照官方文档,入口如下

rowHeight

estimatedRowHeight

至此,已经可以实现SelfSizing Cell的所有步骤,就是这么简单,如果你已经是使用AutoLayout的高手,有啥理由不使用SelfSizing Cell呢。 在这里还是推荐大家尽量多使用AutoLayout,毕竟这项技术还是挺不错的,用多了就会喜欢上这种布局的思路~~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,026评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,655评论 1 296
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,726评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,204评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,558评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,731评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,944评论 2 314
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,698评论 0 203
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,438评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,633评论 2 247
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,125评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,444评论 3 255
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,137评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,103评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,888评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,772评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,669评论 2 271

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,108评论 0 10
  • 偶然间看到一段代码 应该叫类变量,类属性,类成员还是什么的,具体还是上代码吧,我们先在头文件 写好 然后m文件这样...
    十一岁的加重阅读 13,897评论 1 3
  • 公司从小到大,从探索到慢慢成熟,有不同的发展阶段。公司创始人的眼光需要超越公司当下的阶段。 当员工超过20人后,公...
    师照照阅读 330评论 1 0
  • 局域网(Local Area Network,LAN)是指在某一区域内由多台计算机互联成的计算机组。一般是方圆几千...
    廖马儿阅读 541评论 0 1
  • 前几天去了小池钓虾,79元/2小时/杆,两个人最后钓了32只,第一次体验,经验不足,但尚比其他垂钓者好很多。 钓完...
    机器猫与萝卜阅读 419评论 1 0