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):
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With