Why Does Swiftui Uihostingcontroller Have Extra Spacing

On iOS 15, the UIHostingController is adding some weird extra padding to its hosting SwiftUI view (_UIHostingView)

I found out that subclassing UIHostingController as follows fixes the issue with extra padding:

final class HostingController<Content: View>: UIHostingController<Content> {
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()

view.setNeedsUpdateConstraints()
}
}

It also fixes a problem of the UIHostingController not resizing correctly when its SwiftUI View changes size.

UIHostingController should expand to fit contents

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()

// br> 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.

Swift UI: UIHostingController.view is not fit to content view size at iOS 13

Only for iOS 13

Try this:

Every time the view size change, call this:

sampleView.view.removeFromSuperview()
let sampleView = SampleView(object: object)
let hosting = UIHostingController(rootView: sampleView)
view.addArrangedSubview(hosting.view)


Related Topics



Leave a reply



Submit