Skip to content
Commitwise
Menu
iOS Development

Auto Layout: constraints, priorities and self-sizing cells

Lay out UIKit screens that adapt to every iPhone, iPad, language and text size. Constraints with anchors, safe areas and layout guides, intrinsic content size, content hugging and compression resistance, priorities, unsatisfiable and ambiguous layouts, UIStackView, self-sizing cells, the keyboard layout guide, and animating constraints.

intermediate

The core idea with one simple example.Step by step, with more examples and exercises.A cheat sheet: key APIs, gotchas and trade-offs.Internals, trade-offs and production pitfalls.

A console full of “Unable to simultaneously satisfy constraints”. A long name in German that pushes the price off the screen. Table cells that are all the same height no matter how much text they hold, and a Send button hidden behind the keyboard. These are Auto Layout bugs, and every UIKit codebase has had them.

SwiftUI lays out views differently (see SwiftUI layout and animation), but most production apps still have UIKit screens, and interviews for iOS roles regularly include “explain content hugging and compression resistance” or “how do self-sizing cells work?”. The UIKit for SwiftUI developers lesson introduces constraints; this one goes deep.

New to some of these? Open what you need, or skip ahead.

Basics:What is a frame?

A view’s frame is its rectangle in its parent: x, y, width and height, in points. You could set every frame by hand, but then you’d have to recalculate them for every screen size, rotation, language and text size. Auto Layout calculates the frames for you from rules you describe.

Basics:What is a point?

iOS measures layout in points, not pixels. One point is one pixel on old screens, two or three on Retina screens. Working in points means a 44-point button is the same physical size on every iPhone.

Part Not started

Constraints and anchors

A constraint is a rule like “the label’s leading edge is 16 points from the safe area’s leading edge” or “the button’s top is 8 points below the label’s bottom”. Auto Layout solves all the rules together and sets every view’s frame.

For each view, the constraints must answer four questions: where horizontally, where vertically, how wide, how tall. Some views answer the size questions themselves: a UILabel, UIButton or UIImageView has an intrinsic content size, the size of its text or image, so you often only need to position it.

Laying out a view in code always takes three steps:

  1. addSubview(label)
  2. label.translatesAutoresizingMaskIntoConstraints = false (otherwise UIKit adds its own constraints from the frame, and they conflict with yours)
  3. NSLayoutConstraint.activate([...]) with your rules, built from anchors: leadingAnchor, trailingAnchor, topAnchor, bottomAnchor, widthAnchor, heightAnchor, centerXAnchor, centerYAnchor.

Pin content to view.safeAreaLayoutGuide, so it stays clear of the notch, the Dynamic Island and the home indicator, and use leading/trailing rather than left/right, so the layout flips automatically for right-to-left languages like Arabic and Hebrew.

Each constraint is a linear equation, item1.attribute = multiplier × item2.attribute + constant, with a relation (=, ≤, ≥) and a priority. The engine (an incremental Cassowary solver) finds frames satisfying all required constraints while minimizing violations of optional ones. Two failure modes: unsatisfiable (required constraints contradict; UIKit logs the set and breaks one, which one is unspecified) and ambiguous (several solutions; views jump between them or collapse to zero). Debug with constraint identifiers (they appear in logs), the view debugger’s purple warnings, view.hasAmbiguousLayout and exerciseAmbiguityInLayout(), and po view.value(forKey: "_autolayoutTrace") in lldb. Layout guides: safeAreaLayoutGuide, layoutMarginsGuide (respecting directionalLayoutMargins and system minimums), readableContentGuide for comfortable line lengths on iPad, and your own UILayoutGuides instead of invisible spacer views. Activate in batches with NSLayoutConstraint.activate, don’t recreate constraints on every layout pass, and remember that translatesAutoresizingMaskIntoConstraints defaults to true in code and false for views placed in Interface Builder. Views that set frame manually inside layoutSubviews are fine, and sometimes faster, for leaf-heavy custom views.

final class ProfileHeaderView: UIView {
    private let avatar = UIImageView()
    private let nameLabel = UILabel()
    private let followButton = UIButton(configuration: .filled())

    override init(frame: CGRect) {
        super.init(frame: frame)
        nameLabel.font = .preferredFont(forTextStyle: .headline)
        nameLabel.adjustsFontForContentSizeCategory = true      // follows Dynamic Type
        followButton.configuration?.title = "Follow"

        for view in [avatar, nameLabel, followButton] {
            view.translatesAutoresizingMaskIntoConstraints = false
            addSubview(view)
        }

        let margins = layoutMarginsGuide
        NSLayoutConstraint.activate([
            avatar.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
            avatar.topAnchor.constraint(equalTo: margins.topAnchor),
            avatar.bottomAnchor.constraint(lessThanOrEqualTo: margins.bottomAnchor),
            avatar.widthAnchor.constraint(equalToConstant: 56),
            avatar.heightAnchor.constraint(equalTo: avatar.widthAnchor),

            nameLabel.leadingAnchor.constraint(equalToSystemSpacingAfter: avatar.trailingAnchor, multiplier: 1),
            nameLabel.centerYAnchor.constraint(equalTo: avatar.centerYAnchor),

            followButton.leadingAnchor.constraint(greaterThanOrEqualToSystemSpacingAfter: nameLabel.trailingAnchor, multiplier: 1),
            followButton.trailingAnchor.constraint(equalTo: margins.trailingAnchor),
            followButton.centerYAnchor.constraint(equalTo: avatar.centerYAnchor),
        ])
    }

    required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}

Predict the output

A label gets only two constraints: leading and top, pinned to the safe area. Its text is 'Hello'. What size is it?

let label = UILabel()
label.text = "Hello"
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
NSLayoutConstraint.activate([
    label.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor, constant: 16),
    label.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 16),
])

Unable to simultaneously satisfy constraints

Spot the bugA banner that logs conflicts and ignores its constraints

Tap the line with the bug.

override func viewDidLoad() {
    super.viewDidLoad()
    let banner = UIView()
    banner.backgroundColor = .systemYellow
    view.addSubview(banner)
    NSLayoutConstraint.activate([
        banner.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        banner.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        banner.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
        banner.heightAnchor.constraint(equalToConstant: 60),
    ])
}

Deep diveReading a constraint conflict logInterview favorite

The log lists the constraints that can’t all be true, then names the one it broke. Read it bottom-up: find the views by their addresses or, better, by the identifiers you gave them (constraint.identifier = "header.height"; views can have accessibilityIdentifiers too). Look for three usual suspects: NSAutoresizingMaskLayoutConstraint (a view with translatesAutoresizingMaskIntoConstraints still on), UIView-Encapsulated-Layout-Height/Width (the size a table cell, collection cell or stack view imposes, usually conflicting with a required height inside the cell), and two required constraints you added in different places, such as a fixed width plus leading and trailing pinned to a narrower superview.

The fix is rarely deleting one: usually one of them shouldn’t be required. Lowering an inner height constraint to priority 999 lets it give way to the cell’s encapsulated height during the first pass, and the warning disappears without changing the final layout. Add a symbolic breakpoint on UIViewAlertForUnsatisfiableConstraints to stop at the moment it happens.

  • Constraints are linear equations with relations and priorities; the solver satisfies required ones and minimizes optional violations. Unsatisfiable (conflict, one gets broken) vs ambiguous (several solutions).
  • Debug with identifiers, the view debugger, hasAmbiguousLayout, _autolayoutTrace, and a breakpoint on UIViewAlertForUnsatisfiableConstraints; suspects: autoresizing-mask and encapsulated-size constraints.
  • translatesAutoresizingMaskIntoConstraints = false in code; safe area, layout margins, readable content guide, UILayoutGuide instead of spacer views; leading/trailing for RTL.

Check this part

  1. What must you set on a view created in code before adding constraints to it?

  2. Why use leading and trailing instead of left and right?

  3. What is the difference between an unsatisfiable and an ambiguous layout?

  4. A conflict log mentions UIView-Encapsulated-Layout-Height. What is the usual fix?

A constraint is a linear rule between two views' anchors. Each view needs enough of them to fix its position and size, using intrinsic content size where it has one. Turn off translatesAutoresizingMaskIntoConstraints for views laid out in code, pin to the safe area or layout margins, and activate constraints in batches.

Part Not started

Priorities, hugging and compression resistance

Not every rule is equally important. Each constraint has a priority from 1 to 1000. At 1000 (required) it must hold; below that, Auto Layout satisfies it if it can and otherwise gets as close as possible.

Views with an intrinsic size use two priorities to decide who gives way when there’s too much or too little room:

  • Content hugging: how strongly a view resists becoming bigger than its content. Default 250.
  • Compression resistance: how strongly a view resists becoming smaller than its content (and getting truncated). Default 750.

Classic example: a row with a long name and a short date. If the row is too narrow, one of them must be truncated. Both labels have the same default compression resistance, so Auto Layout has no reason to prefer one; it may truncate the date in one row and the name in another. Raise the date’s compression resistance, and the name gets truncated instead, every time.

UIStackView arranges views in a row or column using the same rules, and handles hidden views for you: set isHidden = true on an arranged subview and the stack closes the gap.

Optional priorities let you express preferences: “be 300 wide (750), but never wider than the screen (1000)”; “prefer to sit below the image (999), but stay inside the container (1000)”. Use standard values (.required, .defaultHigh 750, .defaultLow 250, .fittingSizeLevel 50) and small offsets (.defaultHigh + 1) to make intent readable. You can’t change a constraint between required and optional once it’s installed (UIKit throws); toggle isActive on two constraints instead. Interface Builder sets label hugging to 251 by default, so code and storyboard layouts can resolve differently. UIStackView is a constraint generator: distribution (.fill uses hugging and compression priorities to decide who stretches; .fillEqually, .fillProportionally, .equalSpacing), alignment, spacing plus setCustomSpacing(_:after:), isLayoutMarginsRelativeArrangement. It’s cheap since it’s a non-rendering view, but deeply nested stacks in every cell multiply constraints; flatten hot cells. Switching axis based on traitCollection.preferredContentSizeCategory.isAccessibilityCategory turns a horizontal row into a vertical one at large text sizes.

Predict the output

The row is 200 points wide and both texts need 180. The code raises the date label's compression resistance. Which label gets truncated?

nameLabel.text = "Aleksandra Petrović-Nikolić"
dateLabel.text = "12 Nov 2026"
dateLabel.setContentCompressionResistancePriority(.defaultHigh + 1, for: .horizontal)

let row = UIStackView(arrangedSubviews: [nameLabel, dateLabel])
row.axis = .horizontal
row.spacing = 8

A price pushed off the screen

Spot the bugLong product names hide the price

Tap the line with the bug.

NSLayoutConstraint.activate([
    titleLabel.leadingAnchor.constraint(equalTo: margins.leadingAnchor),
    titleLabel.centerYAnchor.constraint(equalTo: margins.centerYAnchor),
    priceLabel.leadingAnchor.constraint(equalTo: titleLabel.trailingAnchor, constant: 8),
    priceLabel.centerYAnchor.constraint(equalTo: margins.centerYAnchor),
])

Deep diveContent hugging vs compression resistanceInterview favorite

Both are the intrinsic content size, turned into two pairs of inequality constraints per axis: width ≤ intrinsicWidth at the hugging priority, and width ≥ intrinsicWidth at the compression-resistance priority. That’s all they are, which is why they compete with your own constraints on equal terms.

Too much room: whichever view has the lower hugging priority stretches. Too little: whichever has the lower compression resistance shrinks. If two views tie in the relevant priority, the layout is ambiguous and the result can differ between runs, devices and iOS versions. Interviewers like the follow-up “a label next to a text field: which should stretch?” Answer: the text field, so give the label higher hugging (251 or more) than the field.

  • Priorities 1–1000; optional constraints express preferences; can’t flip required/optional on an installed constraint, swap two constraints instead.
  • Hugging (default 250, IB labels 251) and compression resistance (750) are inequality constraints from intrinsic size; ties are ambiguous.
  • UIStackView generates constraints from distribution and the same priorities; switch axis for accessibility sizes; flatten nested stacks in hot cells.

Check this part

  1. Two labels in a row don't fit. Which one is truncated?

  2. What priority does a required constraint have?

  3. There is extra horizontal space next to a label and a text field. How do you make the text field stretch?

  4. How do you switch a constraint between required and optional at runtime?

Every constraint has a priority; 1000 is required. Intrinsic size works through content hugging (resist growing, default 250) and compression resistance (resist shrinking, default 750). When two labels compete for space, raise the compression resistance of the one that must stay whole, or Auto Layout's choice is ambiguous. UIStackView uses the same rules.

Part Not started

Self-sizing cells, the keyboard and animation

Self-sizing cells grow with their content: a message cell is taller for a long message. For that to work, Auto Layout must be able to calculate the cell’s height from its content, which means an unbroken chain of vertical constraints from contentView.topAnchor through every view down to contentView.bottomAnchor. Labels need numberOfLines = 0 to wrap. Add subviews to contentView, never to the cell itself.

The keyboard layout guide (iOS 15+) follows the keyboard: pin an input bar’s bottom to view.keyboardLayoutGuide.topAnchor, and it moves up when the keyboard appears and down when it hides, with the system’s own animation. No more listening for keyboard notifications.

To animate a layout change, change the constraint first, then ask the view to lay itself out inside an animation block:

detailsHeight.constant = isExpanded ? 240 : 0
UIView.animate(withDuration: 0.3) {
    self.view.layoutIfNeeded()        // the frames change inside the animation
}

Self-sizing: table views use rowHeight = UITableView.automaticDimension (the default since iOS 11) with a good estimatedRowHeight; compositional layouts use .estimated dimensions; cells answer systemLayoutSizeFitting(_:withHorizontalFittingPriority:verticalFittingPriority:) with width required and height .fittingSizeLevel. Changing a cell’s height after it’s displayed needs tableView.performBatchUpdates(nil) (or a snapshot apply, or invalidateIntrinsicContentSize() with selfSizingInvalidation = .enabledIncludingConstraints on iOS 16+). The layout cycle: setNeedsUpdateConstraints → updateConstraints (batch constraint changes there, mainly for performance), setNeedsLayout → layoutSubviews (frames are known; don’t change constraints that invalidate your own layout or you loop), setNeedsDisplay → draw(_:). Animate by changing constants or toggling prepared constraint sets, then layoutIfNeeded() on the common superview inside UIView.animate or a UIViewPropertyAnimator (interruptible, scrubbable). For trait changes, swap pre-built constraint arrays with NSLayoutConstraint.deactivate/activate from registerForTraitChanges (iOS 17) or traitCollectionDidChange. keyboardLayoutGuide supports followsUndockedKeyboard and tracking-based constraints for iPad floating keyboards. Hosting SwiftUI inside cells: UIHostingConfiguration (iOS 16) for cells, and UIHostingController.sizingOptions = .intrinsicContentSize so hosted views report size changes to Auto Layout.

final class MessageCell: UITableViewCell {
    private let bubble = UIView()
    private let messageLabel = UILabel()
    private let timeLabel = UILabel()

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        messageLabel.numberOfLines = 0                                 // wrap instead of truncating
        messageLabel.font = .preferredFont(forTextStyle: .body)
        messageLabel.adjustsFontForContentSizeCategory = true
        timeLabel.font = .preferredFont(forTextStyle: .caption2)

        for v in [bubble, messageLabel, timeLabel] { v.translatesAutoresizingMaskIntoConstraints = false }
        contentView.addSubview(bubble)                                 // contentView, not the cell
        bubble.addSubview(messageLabel)
        bubble.addSubview(timeLabel)

        NSLayoutConstraint.activate([
            // vertical chain: contentView top → bubble → message → time → bubble → contentView bottom
            bubble.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 4),
            messageLabel.topAnchor.constraint(equalTo: bubble.topAnchor, constant: 8),
            timeLabel.topAnchor.constraint(equalTo: messageLabel.bottomAnchor, constant: 4),
            timeLabel.bottomAnchor.constraint(equalTo: bubble.bottomAnchor, constant: -8),
            bubble.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -4),

            bubble.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor),
            bubble.widthAnchor.constraint(lessThanOrEqualTo: contentView.widthAnchor, multiplier: 0.75),
            messageLabel.leadingAnchor.constraint(equalTo: bubble.leadingAnchor, constant: 12),
            messageLabel.trailingAnchor.constraint(equalTo: bubble.trailingAnchor, constant: -12),
            timeLabel.trailingAnchor.constraint(equalTo: messageLabel.trailingAnchor),
        ])
    }

    required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}

Every cell the same height

Spot the bugLong reviews are cut off

Tap the line with the bug.

contentView.addSubview(starsView)
contentView.addSubview(reviewLabel)
reviewLabel.numberOfLines = 0
NSLayoutConstraint.activate([
    starsView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 12),
    starsView.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor),
    reviewLabel.topAnchor.constraint(equalTo: starsView.bottomAnchor, constant: 8),
    reviewLabel.leadingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.leadingAnchor),
    reviewLabel.trailingAnchor.constraint(equalTo: contentView.layoutMarginsGuide.trailingAnchor),
])

An animation that jumps

UIView.animate animates changes to animatable properties made inside its block. Changing a constraint’s constant changes no frame by itself; frames change in the next layout pass. If that pass happens after the block (at the end of the run loop), the change jumps instead of animating. So the recipe is: change constraints, then call layoutIfNeeded() inside the block, on a view that contains every view whose frame will change (often self.view, not the view whose constraint changed, since siblings move too). Call layoutIfNeeded() once before the block as well, if other pending layout changes shouldn’t be animated along.

Deep diveupdateConstraints, layoutSubviews and layout loopsInterview favorite

UIKit’s layout runs in three deferred passes per frame. Update constraints (updateConstraints, triggered by setNeedsUpdateConstraints) is bottom-up and is where you’d batch constraint changes; Apple’s guidance is to use it only when changing constraints in place is measurably slow. Layout (layoutSubviews, triggered by setNeedsLayout, forced with layoutIfNeeded) is top-down: the engine’s solution is applied to frames, and custom views can position things manually. Display (draw(_:)) renders.

A layout loop happens when layoutSubviews changes something that invalidates layout again: modifying constraints based on the view’s current size, setting a frame that changes intrinsic size, or calling setNeedsLayout on an ancestor. Symptoms: high CPU on an idle screen, layoutSubviews called continuously in Instruments. Fix it by computing such constraints once per size change (in viewWillTransition(to:with:) or on trait changes) and only updating a constant when the new value differs.

  • Self-sizing: unbroken vertical chain to contentView, automaticDimension/.estimated, systemLayoutSizeFitting; resize displayed cells with performBatchUpdates(nil) or self-sizing invalidation (iOS 16).
  • Layout cycle: update constraints → layoutSubviews → draw; avoid changing layout-affecting state in layoutSubviews.
  • Animate constraint changes with layoutIfNeeded() on the common superview inside the block; UIViewPropertyAnimator for interruptible animation; swap prebuilt constraint sets on trait changes.
  • keyboardLayoutGuide (iOS 15); UIHostingConfiguration and sizingOptions for SwiftUI inside Auto Layout.

Check this part

  1. What does a self-sizing table cell need?

  2. How do you keep an input bar above the keyboard on iOS 15+?

  3. A constraint's constant changes inside UIView.animate, but the view jumps. What is missing?

  4. What causes a layout loop?

Self-sizing cells need an unbroken chain of constraints from the content view's top to its bottom. Use the keyboard layout guide for input bars. Animate layout by changing constraints, then calling layoutIfNeeded on the superview inside the animation block. Update constraints, don't recreate them, in hot paths.

Key takeaways

  • Constraints must fix each view’s position and size; intrinsic content size covers size for labels, buttons and images.
  • Set translatesAutoresizingMaskIntoConstraints = false for views laid out in code; pin to the safe area; use leading and trailing.
  • When views compete for space, compression resistance decides who shrinks and hugging decides who grows.
  • Self-sizing cells need a vertical chain from top to bottom of contentView.
  • Animate by changing constraints, then calling layoutIfNeeded() inside the animation block.
  • Think in equations and priorities; know unsatisfiable vs ambiguous and how to read conflict logs.
  • Hugging and compression resistance are just inequality constraints; ties are ambiguous.
  • Know the layout cycle and avoid layout loops; swap prebuilt constraint sets instead of rebuilding.
  • Modern pieces: keyboard layout guide, self-sizing invalidation, UIHostingConfiguration and hosting sizing options.

Finished this page?Nice work, this page is complete!

Mark it as done to track your progress. It's saved in this browser, no account needed.

Its cards are now in your Bites review ⚡
Esc

Type to search the whole site.