Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 348
Luis Ascorbe Avatar asked Sep 21 '21 08:09

Luis Ascorbe


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.

like image 111
Sebastian Osiński Avatar answered Oct 19 '22 01:10

Sebastian Osiński


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
    }
like image 23
Luis Ascorbe Avatar answered Oct 19 '22 01:10

Luis Ascorbe