18

UPDATE: 2022-09-26

This issue has been fixed on iOS 16. Although the issue is still present on iOS 15 even when the project is compiled with the iOS 16 SDK.

Original question:

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.

Luis Ascorbe
  • 1,985
  • 1
  • 22
  • 36

2 Answers2

25

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.

Sebastian Osiński
  • 2,894
  • 3
  • 22
  • 34
4

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
    }
Luis Ascorbe
  • 1,985
  • 1
  • 22
  • 36