Cocoa Autolayout: content hugging vs content compression resistance priority

dmitrynikolaev picture dmitrynikolaev · Apr 6, 2013 · Viewed 215k times · Source

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 ?

Answer

Snowcrash picture Snowcrash · Apr 29, 2013

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