AUTO LAYOUT MAGIC: CONTENT SIZING PRIORITIES

转载:http://krakendev.io/blog/autolayout-magic-like-harry-potter-but-real

One of my personal favorite things about good code and well-designed features is self-documentation. For the most part, a successful implementation of a feature without having to dive into online documentation feels like...well, magic.

Auto Layout however, has a few features that aren't very self-explanatory. Among these features are Content Hugging & Content Compression Priorities. BUT, before we go into these two features, we need to understand something else first -Intrinsic Content Size

INTRINSIC CONTENT SIZE

You may have seen this property onUIViewand it's fairly simple to understand. For most cases, a view knows more about what it's size should be than the system laying it out. Auto Layout takes advantage of this when determining what size a view should be. A view, such as aUILabel, will know what size it's content is. In the case of aUILabel, it determines it from the text. For other cases like aUIImageView, it gets determined through the size of the original image, etc. View's with intrinsic content sizesgenerally size themselves. However, this is not always a hard and fast rule. In many cases, yourNSLayoutConstraints can be defined in a way that can be satisfied in multiple ways. To restrict how many ways constraints can be satisfied and define more strict behaviors, we can take advantage ofcontent huggingandcontent compression resistancepriorities to help a brotha out.

THE MORE YOU LEARN, THE MORE YOU KNOW

Both of these properties can be set along bothVertical&Horizontalaxes. This means that you can set priorities for both the width and height of a view.

Along either of these axes, you also have levels that you can set for them. These levels map to a number from 1-1000 where 1 is aLowpriority and 1000 is aRequiredpriority. These priority values are really important because their values are what determine a view's sizing behavior. What's also important to remember is that they arecomparativevalues. In the cases where there are constraint conflicts between two or more views, Auto Layout looks at these values and sizes them in order from highest priority to the smallest priority.

CONTENT HUGGING PRIORITY

When you want a view to resist growing larger than it's intrinsic content size, this is the property you want to be looking at. Let's take an easy example: two labels (a multi-line title label and a multi-line description label) stacked on top of each other in aUITableViewCelllike so:

Currently, our titleLabel and descriptionLabel have equal vertical content hugging priorities of 250 each. This is fine because of how big the cell currently is, but what happens when we make the cell bigger than that? Which label should grow with it? Should they both grow at the same time? Can you guess which label grows and which hugs it's content? I can't.

"Well, what's the answer?!", you say?

SPOILERS: raising the height of the cell in the storyboard actually produces this result and even gives us a nifty error:

In a situation like our two stacked labels, Auto Layout needs a way to figure out which of the two labels to expand. It does so by inspecting each label's priority behaviors. In the case ofcontent hugging, the label with thelowest priority will loseand in turn, willgrowwith it's container. The label with the higher priority does the inverse; it wins the battle of priorities and keeps it's size to match it's intrinsic content size. If both happen to be equal to each other, then the system can choose any view to expand that it feels like. Undefined behavior like this is never good as it can vary from OS to OS.

In our example, it's obvious that we want our single line title label to be as tall as it's content, and our multi line description label to be flexible in height. To do so, we simply have to make sure the title label'svertical content hugging priorityishigherthan our description label's content hugging priority. By making our titleLabel's content hugging priority higher than our descriptionLabel, we get this result:

Hooray! No Auto Layout issues!

CONTENT COMPRESSION RESISTANCE PRIORITY

When you want a view to resist being resized smaller than it's content, then this is the property that you want to be looking at. As indicated in it's name, a higher Compression Resistance Priority on a viewensures that it doesn't shrinkenough to truncate it's contents.

In the case of our stacked label example, this can happen when the cell shrinks smaller than the contents of our two labels. In a situation like that, Auto Layout needs to figure out which label to shrink first. How it chooses is byshrinking the labelwith thelowercompression resistance. Since both our titleLabel and descriptionLabel's compression resistances are equal, we can't tell right away which label is going to shrink. Which label is going to shrink with the cell? Do they both clip? Well, as it turns out, this happens:

Sad titleLabel is sad.

This result isn't necessarily what we want. In our example, the label we don't want shrinking, again, is the title label since the description label can be truncated if need be. To ensure our title label doesn't truncate it's contents, we want to make sure it's compression resistance priority ishigher thanour description label's compression resistance. This will make sure that Auto Layout will have to shrink thedescriptionlabel if it faces a situation like the one we just came from. By making the compression resistance priority of the titleLabel higher than the description label, we get this nice truncated result:

DOING THE DEED

For both Content Hugging and Content Compression Resistance Priorities, there are two ways to set them: Programmatically & through Interface Builder.

Here's how it looks programmatically:

titleLabel.setContentCompressionResistancePriority(UILayoutPriorityRequired,forAxis:.Horizontal)descriptionLabel.setContentHuggingResistancePriority(UILayoutPriorityDefaultLow,forAxis:.Horizontal)

Interface Builder (as it is for most view related properties) has been by far the easiest way to set them. In your storyboard, navigate to the Size Inspector (where your constraints normally live) and scroll to the bottom. You should see these two fields:

TL;DR

All that said, here's a cute picture from@mokagiothat demonstrates the difference between Content Hugging and Content Compression Resistance at a high level (perfect for a TL;DR):

And in case Mr. Balloon Man wasn't enough of a TL;DR for you, then here you go:

Intrinsic Content Size- Pretty self-explanatory, but views with variable content are aware of how big their content is and describe their content's size through this property. Some obvious examples of views that have intrinsic content sizes areUIImageViews,UILabels, *UIButtons.

Content Hugging Priority- The higher this priority is, the more a viewresists growing largerthan it's intrinsic content size.

Content Compression Resistance Priority- The higher this priority is, the more a viewresists shrinking smallerthan it's intrinsic content size.

CONCLUSION

Content Sizing Priorities have always been a bit of a sore spot for iOS Developers in general. When I first started out, I actually wish I could have had something like this guide to help me out. Luckily enough, I was able to make do by guessing priorities and running a thousand times until it did what I wanted it to do. Hopefully what I've written can help someone out there figure this out for their own. As always, feel free to comment below if I got anything terribly wrong 👾

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

推荐阅读更多精彩内容

  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 8,857评论 0 6
  • 七律喜迎党的 十九大胜利召开 **诗文/红尘一凡 喜值丹香桂馥缨,宏基开拓聚京城。 中枢反腐民心顺,上政扶贫国力升...
    37度女人_8dda阅读 494评论 1 3
  • 第一次相遇,是蝶为花起舞,水为蝶停留。 第一次怒吼,是蝶为花折翅,水为花痛哭。 第一次远走,是蝶为花奔波,水为花付...
    君兮阅读 651评论 24 12