Content Compression and Hugging in Auto Layout

16 May 2013 – Peter Stuart

Continuing from my first post on Auto Layout, I'm going to use the custom avatar view that we made and lay it out in a window with two text fields:

Full size window

When designing a UI, there is often one part of a view which should be the first to start shrinking if the view containing it changes size, or if there isn't enough room in the view to fit all the content. For example, in this window, I would like the text field on the right to always show its full content, and I would like the text field on the left to shrink if necessary.

Before we deal with which text field should shrink, lets set up the UI. We'll create an EPSAvatarView (from the previous post), and two NSTextFields, set up to act like labels. Here are the constraints we'll use to lay them out in the window:

Using, these constraints, at the smallest allowed window size everything is laid out correctly, but the window can grow taller than is necessary to fit the avatar view. This is because the avatar view's content hugging priority (the strength with which it resists being made bigger than its intrinsic content size) is too low. Since we want the avatar view to always be the exact size needed by the avatar, we will set its content compression priority to the highest possible priority, for its horizontal and vertical dimensions:

Once that's done, the window can no longer be resized vertically, but can still be resized horizontally. When it's larger than necessary horizontally, the layout system chooses (pretty much at random) which of the text fields expand in order to fulfill the constraints we've set up. To make the left text field always be the one which is stretched, we can raise the hugging priority of the right text field, to make it resist being sized bigger than its content:

With all these constraints set up, the window can only be resized horizontally, and the left text field will always be the view that is stretched to fulfill the constraints. The window also can't be sized smaller than the minimum size needed to fit all the content. If we want to make it possible for the window to be smaller than the content, and want the left text field to be truncated when that happens, we need to lower its compression resistance priority (the strength with which it resists being made smaller than its intrinsic content size):

Now the window can be sized much smaller—it still needs to fit the avatar view and the right text field, but the left text field can be shrunk to have a width of 0.

You can find the complete example code for this post on GitHub.


Check out more of our posts about Auto Layout.