Friday, September 16, 2016

ios auto layout settings with Hugging and Compression Resistance

Minimal auto layout settings:

For any ios view, the minimal auto layout setting is top (y) and leading space. Once these two values are decided, the auto layout can put the view in the right place.
The width and height will be decided at run time based on the view's intrinsic value. For example, if the view is UILabel, the width and height will be decided based on the label text's content along with the font selected for the label.


Optional width and height constraints:
Sometimes, it is better to fix the view's width or height regardless of the view's intrinsic content.
For example, you may want the label always use first 1/3 width of the line to align all labels on a screen. To do so, you add a proportional equal width constraint with multiplier of 0.3. Or define both leading and trailing space to decide the width based on superview's width.

Content Hugging and Compression Resistance priority 
When the width and height of the view is decided by intrinsic value, instead of fixed by constraints, then at runtime, the multiple constraints may conflict. For example, in the below


There are a leading space constraint between green label to superview, and horizontal space constrait between green label and purple label, and a trailing space constraint between purple label to superview. This works fine at design time, but at runtime, if the actual viewcontroller's width is larger or smaller than the design time viewcontroller's width, then the label view's width has to be changed to satisfy the leading and trailing space constraints. The issue is which label view should change its width?

The xcode interface build has two additional properties Hugging and Compression Resistance to control which view should shrink or expand to meet the runtime constraints requirement.

Both properties have a value of 0 to 1000, the higher the value, the higher the priority. When the size needs to be adjusted at runtime, the view who has lower hugging property value will expand its size to satisfy the constraints requirement, while the view having a higher hugging property value will keep closely hugging itself to its current size. For example, if we give green label' hugging property to 200, and purple label's hugging property to 100, then when running it on a device with bigger width, then the purple label (who has a low hugging value of 100) will grow the width to satisfy the width constraints


Similarly compression resistance property is used to decide if there are not enough width space, which view needs to shrink. The view has a low compression resistance value will shrink first. In this case, the purple label (who has low resistance property of 100) will shrink itself when running on a narrow iphone device as below. While the green label keeps its current width, who has a compression resistance property of 200.


No comments:

Post a Comment