intrinsicContentSize

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

Fill the blank

Fill the blank so Auto Layout picks up the new size when the text changes.

final class TagView: UIView {
    private let label = UILabel()
    var text = "" {
        didSet {
            label.text = text
            ____
        }
    }
    override var intrinsicContentSize: CGSize {
        let size = label.intrinsicContentSize
        return CGSize(width: size.width + 16, height: size.height + 8)
    }
}
Options
Hint 1 of 1

Auto Layout caches the intrinsic size.

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

Show answer

Answer: A invalidateIntrinsicContentSize()

Correct. It tells Auto Layout to ask for the size again.

Why not the others?
  • B setNeedsDisplay(). That redraws content; it doesn't recompute layout size.
  • C layoutIfNeeded(). It runs layout now but with the cached old intrinsic size.
  • D sizeToFit(). It changes the frame directly, which Auto Layout overrides.

30-second answer

intrinsicContentSize is the natural size a view wants from its content, like a label's text size. Auto Layout uses it, together with hugging and compression priorities, so you don't need width and height constraints. In a custom view, override it and call invalidateIntrinsicContentSize() whenever the content changes.

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

Explain intrinsicContentSize.

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

  • Natural size from content
  • Works with priorities
  • Invalidate on change

Deep dive

Return UIView.noIntrinsicMetric for an axis without a natural size.

Labels need preferredMaxLayoutWidth or constraints to wrap.

Self-sizing cells rely on intrinsic sizes of their subviews.

Don't compute it from the view's own frame, which causes loops.

Common mistakes

  • Forgetting to invalidate after content changes.
  • Adding explicit size constraints that fight the intrinsic size.

Senior take & follow-ups

Seniors connect intrinsic size, priorities and self-sizing.

Follow-up questions

Think of your answer first, then open the hint.

  1. What is noIntrinsicMetric?

    Show hint

    No natural size on that axis.

  2. How do self-sizing cells work?

    Show hint

    Estimated sizes plus constraints from content to the cell edges.

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