skip to content

In UIKit, a trip card shows a long driver name beside the fare; how do hugging and compression resistance decide which label truncates or stretches?

level: middleimportance: must knowfreq 78%

answer

  1. intrinsic size becomes two wishes
  2. one wish per axis, per view
  3. too little room versus too much
  4. code-made label: 250 and 750
  5. equal priorities leave UIKit to choose

basics

~20 s

Each label's intrinsic size yields two optional constraints per axis: compression resistance against shrinking and hugging against growing. With too little room the lower compression resistance truncates; with spare room the lower hugging stretches. Equal priorities leave UIKit to choose.

solid answer

~40 s

A `UILabel` reports an `intrinsicContentSize`, and UIKit turns it into two optional constraints per axis: **compression resistance** (do not get smaller than the content) and **content hugging** (do not get bigger). A label created in code reports 250 for horizontal hugging and 750 for horizontal compression resistance, so two labels in a row tie on both. When the row is too narrow, the label with the **lower compression resistance** gives way and truncates; when it is too wide, the one with the **lower hugging** stretches. With a tie, UIKit still has to pick one, and it can be the fare. So state the intent: `fare.setContentCompressionResistancePriority(.required, for: .horizontal)` makes the fare never truncate, and raising its hugging to 251 makes the name take any spare width.

code

swift · 24 lines
swift
import UIKit

@MainActor
func layOutTripRow(name: UILabel, fare: UILabel, in card: UIView) {
    for label in [name, fare] {
        label.translatesAutoresizingMaskIntoConstraints = false
        card.addSubview(label)
    }
    name.lineBreakMode = .byTruncatingTail

    // Too little room: the fare refuses to shrink, so the name truncates.
    fare.setContentCompressionResistancePriority(.required, for: .horizontal)
    // Too much room: the fare hugs tighter (251 > 250), so the name stretches.
    fare.setContentHuggingPriority(.defaultLow + 1, for: .horizontal)

    let margins = card.layoutMarginsGuide
    NSLayoutConstraint.activate([
        name.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
        name.topAnchor.constraint(equalTo: margins.topAnchor),
        fare.leadingAnchor.constraint(equalTo: name.trailingAnchor, constant: 8),
        fare.trailingAnchor.constraint(equalTo: margins.trailingAnchor),
        fare.firstBaselineAnchor.constraint(equalTo: name.firstBaselineAnchor)
    ])
}

go deeper

for a junior

Recall the two names and their direction: compression resistance fights shrinking, hugging fights growing, and the lower value gives way.

for a middle

Explain how intrinsicContentSize becomes optional constraints per axis, the 250 and 750 defaults, and why two labels tie.

for a senior

Diagnose a truncated fare from the priorities alone, pick which view to raise, and avoid a required value that turns a squeeze into a conflict.

for a principal

Argue for a team convention: every row of two text views states its winner explicitly, and layouts are checked at the smallest width and largest text size.

## Where the two priorities come from Some views know how big their content is. A `UILabel` measures its text, a `UIButton` its title and image, a `UIImageView` its image. They report this as `intrinsicContentSize`. UIKit's header describes what happens next: Auto Layout sets up constraints saying that the content should not be **compressed or clipped**, and that the view prefers to **hug** its content tightly. Each of those is an *optional* constraint, created separately for the horizontal and the vertical axis: - **Content compression resistance**: in effect `width >= intrinsic width`, at the view's compression resistance priority. It matters when there is **too little** room. - **Content hugging**: in effect `width <= intrinsic width`, at the view's hugging priority. It matters when there is **too much** room. You read and set them with `contentHuggingPriority(for:)`, `setContentHuggingPriority(_:for:)`, `contentCompressionResistancePriority(for:)` and `setContentCompressionResistancePriority(_:for:)`, passing `.horizontal` or `.vertical`. ## How the solver uses them Priorities run from 1 to 1,000. Auto Layout first satisfies every **required** constraint (1,000), then tries the optional ones from highest to lowest priority, coming as close as it can to any it cannot meet exactly. Priorities only mean something **relative to each other**: a 750 beats a 250 and loses to a 1,000. `UILayoutPriority` names the common levels: `.required` (1000), `.defaultHigh` (750), `.defaultLow` (250) and `.fittingSizeLevel` (50). Because it is a numeric type in Swift, `.defaultLow + 1` gives 251. | Situation | Priority that decides | Who gives way | |---|---|---| | Row too narrow for both texts | compression resistance | the label with the **lower** value shrinks and truncates | | Row wider than both texts | content hugging | the label with the **lower** value stretches | | Both labels equal | neither | UIKit picks; the result may not match your intent | ## The trip card's defaults, and why they bite A `UILabel` made in code reports **250** for horizontal hugging and **750** for horizontal compression resistance; the header names those same two levels as the ones a button uses horizontally. Put a driver name and a fare in a row with `fare.leading = name.trailing + 8` and both pinned to the card's margins, and the two labels **tie on both priorities**. With a long name on a narrow phone, UIKit must shrink one of them, and nothing says it will be the name: the fare can end up truncated or squeezed to nothing. With a short name, it must stretch one, and the fare can drift away from the right edge. The layout is valid in the solver's eyes; it just is not the layout you meant. ## Stating the intent 1. Decide which label must **never** shrink: the fare. Raise its horizontal compression resistance above the name's, to `.required` if it truly must never truncate (then a card too narrow for even the fare produces a constraint conflict instead). 2. Decide which label takes **spare** room: the name. Raise the fare's hugging above the name's, for example to `.defaultLow + 1`, so the name is the one that stretches. 3. Give the label that yields a sensible `lineBreakMode`, such as `.byTruncatingTail`. 4. Test on the narrowest device and the largest Dynamic Type size, where the tie actually shows. Two habits keep this readable in review: - Change the priority of the view that should **win**, and leave a comment saying which way it wins. - Remember the axis: a vertical compression problem (a label clipped in height) is fixed with `.vertical`, not `.horizontal`. ## Inside a stack view A horizontal `UIStackView` with the `.fill` distribution resolves overflow and underflow with the **same** priorities. Its header adds one more rule: when the priorities leave the result ambiguous, it falls back to the order of the arranged subviews. That makes a stack more predictable than hand-written constraints, but the fix is still to set the priorities rather than to rely on order. ## Custom views A custom view that draws its own content should override `intrinsicContentSize` and set sensible defaults for both priorities when it is created; Apple's documentation suggests `.defaultLow` or `.defaultHigh` based on the content. Anyone using the view can then adjust them for a particular layout.

  • Why might setting the fare's compression resistance to .required backfire?
    A priority of 1,000 makes that constraint required. If the card ever becomes narrower than the fare plus its margins, the required constraints contradict each other and UIKit logs a constraint conflict, then breaks one of them. A value such as 999 or `.defaultHigh + 1` still beats the name but leaves the solver a way out.
  • Do these priorities matter for a view that has no intrinsic content size?
    Not on an axis where the view reports `UIView.noIntrinsicMetric`, because there is no intrinsic size to hug or resist. A plain `UIView` reports that for both axes, so its size comes only from explicit constraints.

Two passengers share a bench. One refuses to be squeezed (high compression resistance) and the other is happy to spread out (low hugging): when the bench is short, the less stubborn one gets squeezed; when it is long, the one happy to spread takes the space.

  • Hugging decides who truncates when there is not enough room.
  • Labels already have different default priorities, so a row of two never ties.
  • A higher compression resistance makes a label shrink first.
  • Setting a priority on one axis applies it to both axes.
  • Subview order always decides who stretches in a plain constraint layout.