UIHostingController should expand to fit contents UIHostingController should expand to fit contents swift swift

UIHostingController should expand to fit contents


This plays off what @Rengers was saying, but wanted to include my solution that took me a fair amount of time to figure out.

Hopefully save some time

struct SizingView<T: View>: View {        let view: T    let updateSizeHandler: ((_ size: CGSize) -> Void)    init(view: T, updateSizeHandler: @escaping (_ size: CGSize) -> Void) {        self.view = view        self.updateSizeHandler = updateSizeHandler    }    var body: some View {        view.background(            GeometryReader { proxy in                Color.clear                    .preference(key: SizePreferenceKey.self, value: proxy.size)            }        )        .onPreferenceChange(SizePreferenceKey.self) { preferences in            updateSizeHandler(preferences)        }    }        func size(with view: T, geometry: GeometryProxy) -> T {        updateSizeHandler?(geometry.size)        return view    }}


I encountered the same issue with a similar-ish view hierarchy involving UIHostingController and scroll views, and found an ugly hack to make it work. Basically, I add a height constraint and update the constant manually:

private var heightConstraint: NSLayoutConstraint?...override func viewDidLoad() {    ...    heightConstraint = viewHost.view.heightAnchor.constraint(equalToConstant: 0)    ...}override func viewDidLayoutSubviews() {    super.viewDidLayoutSubviews()    // 😬    viewHost.view.sizeToFit()    heightConstraint?.constant = viewHost.view.bounds.height    heightConstraint?.isActive = true}

This is horrible code, but it's the only thing I found that made it work.


I faced the same issue and none of the suggestions worked for me. Then I found the following class in the SwiftUIX project: https://github.com/SwiftUIX/SwiftUIX/blob/master/Sources/Intermodular/Helpers/UIKit/UIHostingView.swift

This worked perfectly, except for the SwiftUI animations that still work but don't look exactly the same as in a pure SwiftUI context.