swiftuiios15uihostingcontroller

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.


Solution

  • 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.