On iOS 15, the UIHostingController is adding some weird extra padding to its hosting SwiftUI view (_UIHostingView)
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.
UIHostingController should expand to fit contents
I encountered the same issue with a similar-ish view hierarchy involving UIHostingController
and scroll views, and found an ugly hack to make it work. Basically, I add a height constraint and update the constant manually:
private var heightConstraint: NSLayoutConstraint?
...
override func viewDidLoad() {
...
heightConstraint = viewHost.view.heightAnchor.constraint(equalToConstant: 0)
...
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// br> viewHost.view.sizeToFit()
heightConstraint?.constant = viewHost.view.bounds.height
heightConstraint?.isActive = true
}
This is horrible code, but it's the only thing I found that made it work.
Swift UI: UIHostingController.view is not fit to content view size at iOS 13
Only for iOS 13
Try this:
Every time the view size change, call this:
sampleView.view.removeFromSuperview()
let sampleView = SampleView(object: object)
let hosting = UIHostingController(rootView: sampleView)
view.addArrangedSubview(hosting.view)
Related Topics
How to Handle Hash Collisions for Dictionaries in Swift
How to Make a Extension for Array of Specific Type in Swift
Calling a Function Defined in Assembly from Swift
Map or Reduce with Index in Swift
Does Swift Compile to Native Code
How to Compare Just the Time of a Date in Swift
Swift 2: !, ? -" Value of Optional Type "..." Not Unwrapped"
Is There a Daylight Savings Check in Swift
What Makes a Property a Computed Property in Swift
Swiftui: How to Make Entire Shape Recognize Gestures When Stroked
How to Set an Environment Object in Preview
How to Use a Variadic Closure in Swift