Tuesday, December 1, 2015

Content hugging vs. compression resistance in Apple's auto layout


Auto layout is a great way to define UI when developing Apple software.

"Auto" means it does a lot by itself. You define some rules and the engine is calculating the size of the screen elements.

There is one case when it cannot.

Consider two labels, side by side:



All is good, each label is taking as little space as possible.

We would like to extend the labels in such a way that they will cover the whole screen, with a little bit of space on the sides and at the back.

Layout engine is confused this time: which one should grow? You might say: equally. That might be okay, but what if the labels contain different amount of text?



So in this case the layout needs more information.

One of the values you can set up for labels is Content Hugging. We can translate this with "I want to be small"

In the labels above, the value of "I want to be small" is 251, by default. The value can be between 1 and 1000. Just like a a fight where it does not matter who is stronger, but the ones who can run faster, the value does not matter, but who is bigger.

So, in the example above, if we add the constraints, we'll have an ambiguity:



The constraints will be displayed in red.

The solution is to increase the value of Content Hugging for the labels that wants to be small in a stronger way. For example, increase Content Hugging for Label 1 to 252 will result in:




Similar for Content Compression Resistance which can be translated with "I want to be big". This comes into play when the labels contain more text than they can hold.

For example:



The layout engine needs to know which one to squish, either by truncating the text or by reducing the font, depending on the label property.

So, in this case it is looking at "I want to be big" value which is 750 by default. Increase one and it will blow the other one to smithereens.

For example, increase the one for the first label to 751 and you will get:



The same concepts apply for horizontal as well for vertical constraints.




No comments:

Post a Comment