DEV Community

Agoi Abel Adeyemi
Agoi Abel Adeyemi

Posted on

1

View Properties use by Auto Layout

Intrinsic content size, Compression Resistance Priority, Content Hugging Priority

There are some views that automatically size themselves base on the content they hold, This is referred to as their intrinsic content size. E.G A button’s intrinsic content size is the size of its title plus a small margin. Not all views have an intrinsic content size. For views that do, the intrinsic content size can define the view’s height, it’s width or both.

Let say we have a button with the text “Click Me”.

We definitely don’t want the button to be smaller than the text inside it, Otherwise the text would be clipped. This is know as Compression Resistance Priority.

The higher a view’s Compression Resistance Priority, the more the view resists growing larger than its intrinsic content size.

Still on the “Click Me” button, If we don’t want the button to be really bigger than the content inside it like the image below:

If we want the button to hug its content without too much padding, we have to increase the Content Hugging Priority.

The higher a view’s Content Hugging Priority is, the more the view resists growing larger than its intrinsic content size.

We can set the content hugging and compression resistance priority programmatically like below:

newView.setContentCompressionResistancePriority(.defaultHigh, for: .vertical)
newView.setContentHuggingPriority(.defaultLow, for: .horizontal)

The two methods take two parameters which are the UILayoutPriority and the UILayoutConstraintAxis. The priority level can be required, defaultHigh, defaultLow, fittingSizeLevel where required is the highest and fittingSizeLevel is the lowest. The UILayoutConstraintAxis can either be a vertical or horizontal axis.

I will write another article on UIStackview, after which I will show ways to programmatically code different views. Thanks for reading.

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs