Ios – the content compression resistance and content hugging of a UIView

autolayoutcocoa-touchiosuiview

What is the content compression resistance and content hugging of a UIView? How do these relate to the intrinsic content size of a view?

Best Answer

Taken from objc.io's excellent Advanced Auto Layout Toolbox article:

Intrinsic Content Size

The intrinsic content size is the size a view prefers to have for a specific content it displays. For example, UILabel has a preferred height based on the font, and a preferred width based on the font and the text it displays. A UIProgressView only has a preferred height based on its artwork, but no preferred width. A plain UIView has neither a preferred width nor a preferred height.

Compression Resistance and Content Hugging

Each view has content compression resistance priorities and content hugging priorities assigned for both dimensions. These properties only take effect for views which define an intrinsic content size, otherwise there is no content size defined that could resist compression or be hugged.

Behind the scenes, the intrinsic content size and these priority values get translated into constraints. For a label with an intrinsic content size of { 100, 30 }, horizontal/vertical compression resistance priority of 750, and horizontal/vertical content hugging priority of 250, four constraints will be generated:

H:[label(<=100@250)] 
H:[label(>=100@750)]
V:[label(<=30@250)]
V:[label(>=30@750)]

If you’re not familiar with the visual format language for the constraints used above, you can read up about it in Apple’s documentation. Keeping in mind that these additional constraints are generated implicitly helps to understand Auto Layout’s behavior and to make better sense of its error messages.

Here's another StackOverflow question that addresses the difference between content compression resistance & content hugging: Cocoa Autolayout: content hugging vs content compression resistance priority