Content hugging and compression resistance

UIKit Mid-level Swift 5.0+ iOS 17+ Reviewed By Alok Singh

Predict the output

A name label and a date label sit in a row with default priorities. The name is very long. Which one truncates?

let name = UILabel()   // "A very long display name..."
let date = UILabel()   // "31 Oct"
// name.leading = container.leading
// date.leading = name.trailing + 8
// date.trailing = container.trailing
// both labels keep default hugging and compression priorities
Options
Hint 1 of 1

Compare the two labels' priorities.

Choose an answer, then open Show answer below to check it.

Show answer

Answer: C Either one: the layout is ambiguous because the priorities are equal

Correct. Raise the date's compression resistance (say 751) so the name truncates.

Why not the others?
  • A Always the name label. Only if you raise the date's compression resistance above the name's.
  • B Always the date label. Nothing makes the date lower priority than the name.
  • D Neither: the container grows. The container's edges are fixed in this layout.

30-second answer

They tell Auto Layout how a view with an intrinsic size behaves when space doesn't match. Hugging priority resists growing larger than its content; compression resistance resists shrinking smaller. When two labels compete for space, raise the compression resistance of the one that must stay readable, or the hugging of the one that should stay tight.

Practise saying it · 30 s. No recording, just a timer

Explain hugging vs compression resistance.

Say your answer out loud, then check which of these points you covered:

  • Hugging resists growing
  • Compression resists shrinking
  • Break ties explicitly

Deep dive

Defaults: hugging 250, compression resistance 750 (for labels in code).

Equal priorities between competing views produce an ambiguous result.

Set them per axis: setContentCompressionResistancePriority(.required, for: .horizontal).

UIStackView distribution interacts with these priorities.

Common mistakes

  • Leaving equal priorities and getting random truncation.
  • Using fixed widths instead of priorities.

Senior take & follow-ups

Seniors resolve competition explicitly, so the result never depends on luck.

Follow-up questions

Think of your answer first, then open the hint.

  1. Which label should truncate in a name + date row?

    Show hint

    Usually the name; protect the date's compression resistance.

  2. What does hugging do in a stack view with fill distribution?

    Show hint

    The lowest-hugging view stretches.

From the author

Catalog - UI

Made by the author: browse UIKit components with live demos, and copy their code snippets into your project.

Suggest a fix if something here is wrong or out of date.