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

Viewed 2544

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

See screenshot below (Blue = extra space, Red = actual view’s):

enter image description here

Does anyone know why this happens?

I've reported this bug, Apple folks: FB9641883

PD: I have a working project reproducing the issue which I attached to the Feedback Assistant issue. If anyone wants it I can upload it too.

2 Answers

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.

I’ve tried to find why is this happening without luck. The only thing I’ve found to fix it is setting a height constraint to its intrinsic content size in a subclass of UIHostingController:

    private var heightConstraint: NSLayoutConstraint?

    override open func viewDidLoad() {
        super.viewDidLoad()
        if #available(iOS 15.0, *) {
            heightConstraint = view.heightAnchor.constraint(equalToConstant: view.intrinsicContentSize.height)
            NSLayoutConstraint.activate([
                heightConstraint!,
            ])
        }
    }

    override open func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        heightConstraint?.constant = view.intrinsicContentSize.height
    }
Related