In UIKit, a custom fare badge view overrides intrinsicContentSize, yet keeps its old width after the fare text changes; why, and what is the fix?
answer
- UIKit has to be told
- one call marks the size stale
- layout and redraw are separate passes
- size from content, never the frame
- plain views report minus one
basics
~20 sAuto Layout uses the intrinsicContentSize it last read until the view says it changed, and the badge never said so. Call invalidateIntrinsicContentSize() whenever the text changes; setNeedsLayout() or setNeedsDisplay() alone rerun layout or drawing with the old size.
solid answer
~40 sA custom view that draws its own text has to tell Auto Layout how big it wants to be, so it overrides `intrinsicContentSize`. UIKit turns that size into hugging and compression resistance constraints, and the header says to call `invalidateIntrinsicContentSize()` when something changes that affects it, "otherwise UIKit won't notice that it changed". So the `fareText` setter must call `invalidateIntrinsicContentSize()` and, because the badge draws itself, `setNeedsDisplay()` for the new pixels. `setNeedsLayout()` only schedules another layout pass with the size UIKit already has. The size must come from the content, not the frame, and a dimension the view has no opinion on returns `UIView.noIntrinsicMetric`, which is what a plain `UIView` reports for both. A `UILabel` or `UIButton` already does all of this for you.
code
swift · 25 linesimport UIKit
final class FareBadgeView: UIView {
var fareText = "" {
didSet {
guard fareText != oldValue else { return }
invalidateIntrinsicContentSize() // without this the old width stays
setNeedsDisplay()
}
}
private let font = UIFont.preferredFont(forTextStyle: .headline)
private let padding = UIEdgeInsets(top: 4, left: 10, bottom: 4, right: 10)
override var intrinsicContentSize: CGSize {
let text = (fareText as NSString).size(withAttributes: [.font: font])
return CGSize(width: ceil(text.width) + padding.left + padding.right,
height: ceil(text.height) + padding.top + padding.bottom)
}
override func draw(_ rect: CGRect) {
(fareText as NSString).draw(
at: CGPoint(x: padding.left, y: padding.top),
withAttributes: [.font: font, .foregroundColor: UIColor.label])
}
}go deeper
Recall that a custom view tells Auto Layout its natural size through intrinsicContentSize, and that plain views have none.
Explain how the size becomes hugging and compression resistance constraints, and the three passes: update constraints, layout and display.
Diagnose a stale size at once: the missing invalidateIntrinsicContentSize() call, a size computed from bounds, or a redraw mistaken for a relayout.
Set the standard for reusable custom views: intrinsic size from content only, default priorities chosen on creation, and invalidation in every setter that changes size.
## What intrinsic content size is `intrinsicContentSize` is the size a view would like to be based only on its own content: the text a label shows, the image an image view holds. It is a read-only property you override in a subclass. Apple's header gives a single-line text field as the typical case: the layout system does not understand text, so the view has to tell it how much room its content needs. From that size UIKit creates two optional constraints per axis: one resisting compression below the size and one hugging the content so the view does not grow beyond it, at the view's compression resistance and hugging priorities. That is how a label can sit in a row with only its position constrained. A plain `UIView` returns `UIView.noIntrinsicMetric` (−1) for both width and height: it has no content of its own, so its size must come from constraints. A custom view can return a real width and `noIntrinsicMetric` for height, or the reverse. ## Why the badge keeps its old width Auto Layout builds constraints from the size it read and keeps using them until the view reports a change. The header is explicit about `invalidateIntrinsicContentSize()`: call it *when something changes that affects the intrinsicContentSize. Otherwise UIKit won't notice that it changed.* The badge's computed property does return the new width, but nothing told UIKit to use it. The fix is in the setter: 1. Store the new text. 2. Call `invalidateIntrinsicContentSize()`, so Auto Layout rebuilds the content-size constraints from the new value. 3. Call `setNeedsDisplay()`, because the badge draws its text in `draw(_:)` and the old pixels stay until it redraws. 4. Skip both when the value has not changed, to avoid pointless passes. ## Three passes, three different requests UIKit renders a window in three passes, as the `UIView` header lists them: **update constraints**, **layout**, **display**. Each has its own request method, and confusing them is the root of this bug: | Call | What it schedules | Tells UIKit the intrinsic size changed? | |---|---|---| | `invalidateIntrinsicContentSize()` | new content-size constraints for this view | yes, that is its job | | `setNeedsUpdateConstraints()` | a call to your `updateConstraints()` override | no | | `setNeedsLayout()` | a call to `layoutSubviews()` on the next update cycle | no | | `setNeedsDisplay()` | a call to `draw(_:)` | no | `layoutIfNeeded()` runs any pending layout immediately, but without the invalidation it still works from the old size. ## Rules for a correct override - **Content only.** The documentation says the size must be independent of the frame: there is no way to tell the layout system through this property that a changed width implies a changed height. Do not read `bounds` inside it. - **This view only.** The header says intrinsic size concerns data in the view itself, not in other views. - **Round up.** Measured text has fractional sizes; rounding up with `ceil` avoids clipping the last glyph. - **Set priorities.** Give the view sensible hugging and compression resistance on creation; Apple suggests `.defaultLow` or `.defaultHigh` depending on the content. - **Prefer a constraint when the size is fixed.** The header notes that if a dimension never changes with content, a constant width or height constraint does the job without an override. One more subtlety: constraints relate a view's **alignment rect**, which equals the frame unless the view says otherwise. If the badge later gains a drop shadow drawn outside its pill, override `alignmentRectInsets` so the pill, not the shadow, lines up with the fare label. ## updateConstraints() is a different tool Overriding `updateConstraints()` is for changing your *own* constraints in a batch, when changing them in place is too slow or produces redundant changes. Apple's documentation adds three rules: schedule it with `setNeedsUpdateConstraints()`, never call `setNeedsUpdateConstraints()` from inside it (that creates a feedback loop), and call `super.updateConstraints()` as the **final** step. Most code should simply change a constraint's `constant` right where the change happens. The fare badge needs none of this; invalidating its intrinsic size is the whole fix.
- The badge is an arranged subview of a horizontal UIStackView; does anything change?No. Apart from fillEqually, a stack's distributions size arranged views from their intrinsic content size, so the stack also learns the new width only after `invalidateIntrinsicContentSize()`. Once it is called, the stack re-lays out its row on the next pass.
- When is overriding updateConstraints() worth it instead?Only when you change your own constraints so often, or so wastefully, that doing it in place is too slow. You schedule it with `setNeedsUpdateConstraints()`, update only what changed, never schedule another pass from inside it, and call `super.updateConstraints()` last.
- Calling setNeedsLayout() makes UIKit pick up a changed intrinsicContentSize.
- A plain UIView reports a zero intrinsic content size.
- intrinsicContentSize may be computed from the view's current bounds.
- updateConstraints() must call super first, before any changes.
- A view's intrinsic size should include the sizes of neighbouring views.