skip to content

In UIKit, a SwiftUI banner hosted in a UIHostingController inside a UIStackView keeps its first size after its text changes; why, and how do sizingOptions fix it?

level: seniorimportance: should knowfreq 50%

answer

  1. Auto Layout only asks when told
  2. ideal size vs intrinsic size
  3. an option set from iOS 16
  4. popovers read preferredContentSize
  5. the other direction: sizeThatFits

basics

~20 s

Auto Layout keeps using a view's intrinsic content size until the view invalidates it. Setting the hosting controller's sizingOptions to .intrinsicContentSize, iOS 16, makes its view invalidate that size when the SwiftUI content's ideal size changes.

solid answer

~40 s

A `UIStackView` sizes arranged subviews from Auto Layout, which reads a view's `intrinsicContentSize` and does not notice a change until the view calls `invalidateIntrinsicContentSize()`. When the hosted SwiftUI content grows, nothing tells UIKit unless the hosting controller is asked to track it. `UIHostingController.sizingOptions` (iOS 16) is an option set: `.intrinsicContentSize` makes the hosting view invalidate its intrinsic content size whenever the content's ideal size changes, so Auto Layout re-measures; `.preferredContentSize` keeps the controller's `preferredContentSize` equal to that ideal size, which popovers and custom containers read. Embed the controller as a child so containment is right. In the opposite direction, a `UIViewRepresentable` can implement `sizeThatFits(_:uiView:context:)` (iOS 16) to answer SwiftUI's size proposal itself.

code

swift · 31 lines
swift
import SwiftUI
import UIKit

struct DeliveryBanner: View {
    let message: String
    var body: some View {
        Label(message, systemImage: "shippingbox")
            .padding()
    }
}

final class OrderSummaryViewController: UIViewController {
    private let stack = UIStackView()
    private lazy var banner = UIHostingController(
        rootView: DeliveryBanner(message: "Arrives Tuesday")
    )

    override func viewDidLoad() {
        super.viewDidLoad()
        stack.axis = .vertical
        // Auto Layout reads the SwiftUI content's ideal size, and re-reads it when it changes.
        banner.sizingOptions = .intrinsicContentSize
        addChild(banner)
        stack.addArrangedSubview(banner.view)
        banner.didMove(toParent: self)
    }

    func updateBanner(to message: String) {
        banner.rootView = DeliveryBanner(message: message)
    }
}

go deeper

for a junior

Recall that hosted SwiftUI content does not resize its UIKit container by itself; a hosting controller option controls it.

for a middle

Explain the two options: .intrinsicContentSize for Auto Layout parents, .preferredContentSize for popovers and containers that read the controller.

for a senior

Diagnose a stale size by asking who measures the view and what tells them to measure again, in both directions across the boundary.

for a principal

Decide where measurement lives in mixed screens and keep width-dependent layouts measured with sizeThatFits rather than one intrinsic size.

## Who measures a hosted SwiftUI view When a SwiftUI view is hosted in a `UIHostingController` and its view sits in a UIKit layout, **UIKit decides its size**. A `UIStackView`, like any Auto Layout parent, sizes an arranged subview from its constraints and its **intrinsic content size**, the size a view reports it naturally wants. Auto Layout does not poll. UIKit's own header comment on `invalidateIntrinsicContentSize()` says to call it when something changes that affects the intrinsic content size, "otherwise UIKit won't notice that it changed". So when the SwiftUI banner's message grows from "Arrives Tuesday" to a two-part delivery note, the SwiftUI content wants more room, but unless something invalidates the hosting view's intrinsic size, the stack view keeps the first answer. That is the symptom: the content is clipped or leaves a gap. ## sizingOptions `UIHostingController.sizingOptions`, added in **iOS 16**, tells the controller which UIKit size mechanisms should **track the SwiftUI content's ideal size**. Its type, `UIHostingControllerSizingOptions`, is an option set with two members: | Option | What it keeps up to date | Consumer that reads it | |---|---|---| | `.intrinsicContentSize` | The hosting view invalidates its intrinsic content size when the ideal size changes | Auto Layout parents: stack views, constraint-based layouts | | `.preferredContentSize` | The controller's `preferredContentSize` follows the ideal size | Popovers, custom-sized sheets, container controllers that size children from it | The fix for the banner is therefore one line before the controller is added: `banner.sizingOptions = .intrinsicContentSize`. Because it is an option set, a controller used in both kinds of context can set `[.intrinsicContentSize, .preferredContentSize]`. Getting the rest of the embedding right matters too: 1. **Embed as a child view controller**: `addChild(banner)`, add `banner.view` to the stack view, `banner.didMove(toParent: self)`. 2. **Change content through the root view**: assign a new `rootView`, or let the view observe a model. Either way SwiftUI recomputes the ideal size, and the sizing option reports it. 3. **Do not set the hosted view's frame by hand** after each change. It fights Auto Layout and goes stale again at the next change. ## Width-dependent content An intrinsic content size is **one size with no width input**. That suits a banner with a short label. For content whose height depends on the width UIKit gives it, such as long wrapping text, measure for a specific width instead: - `UIHostingController.sizeThatFits(in:)` returns the size the SwiftUI content wants for a proposed size, for example the column width and a very large height; - use that result to size a table header, a self-sizing container or a height constraint. ## The opposite direction: a UIKit view inside SwiftUI Sizing crosses the boundary the other way too. When SwiftUI lays out a `UIViewRepresentable`, it proposes a size and the wrapped UIKit view answers. By default SwiftUI sizes the wrapped view from its intrinsic content size, taking its hugging and compression-resistance priorities into account. When that is not enough, for example a multi-line `UILabel` whose height depends on the proposed width, implement: - `sizeThatFits(_:uiView:context:)` (iOS 16), which receives a `ProposedViewSize` and returns the `CGSize` to use, or `nil` to keep the default behaviour. What not to do here is the mirror of the UIKit-side mistake: Apple's documentation warns that SwiftUI fully controls the wrapped view's center, bounds, frame and transform, so setting them yourself from `updateUIView` is undefined behaviour. ## Before iOS 16 `sizingOptions` and the representable `sizeThatFits(_:uiView:context:)` requirement are both **iOS 16** APIs. Code that still supports earlier releases has to invalidate sizes manually, for example by measuring the hosted content after each change and updating a height constraint, which is exactly the bookkeeping the iOS 16 options remove. ## Diagnosing a stale size When a hosted view or a wrapped view keeps the wrong size, ask three questions in order: 1. **Who measures this view?** Auto Layout, a popover, a container controller, or SwiftUI's layout. 2. **Which size does that consumer read?** Intrinsic content size, `preferredContentSize`, or a representable's answer to a proposal. 3. **What tells it to measure again?** A sizing option, an invalidation, a reconfigure, or nothing at all. In the banner's case the answers are Auto Layout, the intrinsic content size, and nothing, which points straight at `.intrinsicContentSize`.

  • When would you choose .preferredContentSize instead of .intrinsicContentSize?
    When the consumer reads the controller, not the view: a popover, a form sheet with a custom size, or a container controller that sizes children from `preferredContentSize`. With `.preferredContentSize` the hosting controller keeps that property equal to the SwiftUI content's ideal size, so the popover follows the content.
  • How do you measure hosted SwiftUI content for a fixed width without putting it on screen?
    Call `sizeThatFits(in:)` on the hosting controller with the width and a large height; it returns the size the SwiftUI content wants for that proposal. This suits content whose height depends on the width, which a single intrinsic content size cannot express.

  • Expecting Auto Layout to notice a SwiftUI content change without any size invalidation.
  • Setting the hosted view's frame by hand after every rootView change.
  • Using .preferredContentSize when the parent is an Auto Layout stack view.
  • Believing sizingOptions exists before iOS 16.
  • Thinking a representable's frame should be set inside updateUIView to size it.

Assumes the iOS 27 SDK; sizingOptions and the representable sizeThatFits(_:uiView:context:) requirement both arrived in iOS 16, so earlier targets need manual size invalidation.