ChatGPT解决这个技术问题 Extra ChatGPT

Cocoa Autolayout: content hugging vs content compression resistance priority

I can't find a clear answer on Apple documentation regarding Cocoa Autolayout about the difference between content hugging and compression resistance.

Can somebody explain their usages and difference ?

One of life's major mysterious is why they didn't call it simply "Expansion Resistance". The two qualities are nothing more than "Expansion Resistance" and "Compression Resistance". The "hugging" terminology is insane.
If you have too much room then content-hugging: would fight against having white space . It would just force the view to get around you. But if you don't have too much space, and instead have very little place then content-compressions-resistance would fight against your view from not being able to show all its content, e.g. labels would get truncated.

n
ncica

A quick summary of the concepts:

Hugging => content does not want to grow

Compression Resistance => content does not want to shrink

Example:

Say you've got a button like this:

[       Click Me      ]

and you've pinned the edges to a larger superview with priority 500.

Then, if Hugging priority > 500 it'll look like this:

[Click Me]

If Hugging priority < 500 it'll look like this:

[       Click Me      ]

If the superview now shrinks then, if the Compression Resistance priority > 500, it'll look like this

[Click Me]

Else if Compression Resistance priority < 500, it could look like this:

[Cli..]

If it doesn't work like this then you've probably got some other constraints going on that are messing up your good work!

E.g. you could have it pinned to the superview with priority 1000. Or you could have a width priority. If so, this can be helpful:

Editor > Size to Fit Content


What if hugging priority == 500?
I'd assume (but that's usually not a good idea) it'd be treated as >500 like typical rounding behavior. Haven't tested that though.
most likely you'll get "Unable to simultaneously satisfy constraints" warning in runtime
@bradley.ayers To MaxDesyatov's comment, that will only happen if you have conflicting constraints with Required priority (1000). If two lower-priority constraints conflict, the solution is ambiguous so the Auto Layout engine will just pick one valid solution and that's what you'll see (no warnings). Obviously this isn't good, because it's now up to the internal implementation of the Auto Layout engine to choose how your layout looks, and theoretically this could change from one iOS version to the next!
The content hugging priority default is 250, and the content compression resistance default is 750. So why use 500?
o
onmyway133

Take a look at this video tutorial about Autolayout, they explain it carefully

https://i.stack.imgur.com/6GelD.png


@fatuhoku can you check again, this video is free
Hugging vs. Resistance discussion starts at about the 13:15 point in the video.
@onmyway133 this is perfect video, but unfortunately there is no example how Ray uses it.
@MatrosovAlexander I think a very practical example would be Dynamic cell height with Autolayout fantageek.com/1468/…
He shows how to use the compression resistance at 18:05
S
SparkyRobinson

https://i.stack.imgur.com/bTZMz.jpg

source: @mokagio

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 are UIImageViews, UILabels, UIButtons.

Content Hugging Priority - The higher this priority is, the more a view resists growing larger than its intrinsic content size.

Content Compression Resistance Priority - The higher this priority is, the more a view resists shrinking smaller than its intrinsic content size.

Check here for more explanation: AUTO LAYOUT MAGIC: CONTENT SIZING PRIORITIES


The illustration is nice but misleading to say the least. The top guy should say "I'm not gonna (let ME) grow". The child view defines on its own that it doesn't want to grow through it's content hugging behavior. There is no exogenic force (like the illustrated hands) that stop it from growing. That is a big difference.
I'm up voting this just because I love the illustration.
This is why I love Stack Overflow… Snowcrash's description plus this illustration by mokagio = best explanation of these properties anywhere (including Apple's own documentation).
@Manuel I don't think it's child view and parent view here. Rather the rectangle is the view and the person is the implicitly generated system constraint trying to achieve the desired behaviour (hugging or compression resistance) with set priority. So the illustration is still right.
B
Bridger Maxwell

Let's say you have a button with the text, "Click Me". What width should that button be?

First, you definitely don't want the button to be smaller than the text. Otherwise, the text would be clipped. This is the horizontal compression resistance priority.

Second, you don't want the button to be bigger than it needs to be. A button that looked like this, [ Click Me ], is obviously too big. You want the button to "hug" its contents without too much padding. This is the horizontal content hugging priority. For a button, it isn't as strong as the horizontal compression resistance priority.


r
rob mayoff

If view.intrinsicContentSize.width != NSViewNoIntrinsicMetric, then auto layout creates a special constraint of type NSContentSizeLayoutConstraint. This constraint acts like two normal constraints:

a constraint requiring view.width <= view.intrinsicContentSize.width with the horizontal hugging priority, and

a constraint requiring view.width >= view.intrinsicContentSize.width with the horizontal compression resistance priority.

In Swift, with iOS 9's new layout anchors, you could set up equivalent constraints like this:

let horizontalHugging = view.widthAnchor.constraint(
    lessThanOrEqualToConstant: view.intrinsicContentSize.width)
horizontalHugging.priority = view.contentHuggingPriority(for: .horizontal)

let horizontalCompression = view.widthAnchor.constraint(
    greaterThanOrEqualToConstant: view.intrinsicContentSize.width)
horizontalCompression.priority = view.contentCompressionResistancePriority(for: .horizontal)

Similarly, if view.intrinsicContentSize.height != NSViewNoIntrinsicMetric, then auto layout creates an NSContentSizeLayoutConstraint that acts like two constraints on the view's height. In code, they would look like this:

let verticalHugging = view.heightAnchor.constraint(
    lessThanOrEqualToConstant: view.intrinsicContentSize.height)
verticalHugging.priority = view.contentHuggingPriority(for: .vertical)

let verticalCompression = view.heightAnchor.constraint(
    greaterThanOrEqualToConstant: view.intrinsicContentSize.height)
verticalCompression.priority = view.contentCompressionResistancePriority(for: .vertical)

You can see these special NSContentSizeLayoutConstraint instances (if they exist) by printing view.constraints after layout has run. Example:

label.constraints.forEach { print($0) }

// Output:
<NSContentSizeLayoutConstraint:0x7fd82982af90 H:[UILabel:0x7fd82980e5e0'Hello'(39)] Hug:250 CompressionResistance:750>
<NSContentSizeLayoutConstraint:0x7fd82982b4f0 V:[UILabel:0x7fd82980e5e0'Hello'(21)] Hug:250 CompressionResistance:750>

should it not be: let verticalCompression = view.heightAnchor.constraint( greaterThanOrEqualToConstant: view.intrinsicContentSize.height)
Yes, I made a copy/paste error. I have corrected it. Thank you for letting me know.
d
dev gr

Content Hugging and Content Compression Resistence Priorities work for elements which can calculate their size intrinsically depending upon the contents which are coming in.

From Apple docs:

https://i.stack.imgur.com/xzqgz.png


I'm confused. For a textView that doesn't have scrolling enabled. Does that mean per user typing the intrinsic size would change?
@Honey I think with correct constraints set and scrolling disabled, text view should be able to tell intrinsic height.
That didn't answer my question. You mean if I type a lot a lot, more than the current size of the textView....does the textView expand automatically and change the intrinsic size?
Try it yourself. Give textview a fixed width and disable the scroll and check for desired behaviour. Refer stackoverflow.com/a/21287306/1526629 for more answers.
N
Naishta

The Content hugging priority is like a Rubber band that is placed around a view. The higher the priority value, the stronger the rubber band and the more it wants to hug to its content size. The priority value can be imagined like the "strength" of the rubber band

And the Content Compression Resistance is, how much a view "resists" getting smaller The View with higher resistance priority value is the one that will resist compression.


a
ahmed

contentCompressionResistancePriority – The view with the lowest value gets truncated when there is not enough space to fit everything’s intrinsicContentSize

contentHuggingPriority – The view with the lowest value gets expanded beyond its intrinsicContentSize when there is leftover space to fill


I always remember this now and ever since have had no issues. Resistance priority is important when there is not enough space to fit elements. Hugging priority is important when there is too much space.

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now