Ran into this problem yesterday, too.
I am presenting a modal UINavigationController
with a UIViewController
as rootViewController
, which embeds a SwiftUI View via UIHostingController
.
Setting the usual setNavigationBarHidden
in viewDidAppear
of the UIViewController
stops working as soon as the SwiftUI View is embedded.
Overview:
Root ViewController: setNavigationBarHidden in viewWillAppear
Navigation Bar Visible:
UINavigationController > root UIViewController > embedded UIHostingController
Navigation Bar Invisible:
UINavigationController > root UIViewController > no UIHostingController
After some debugging I realized that the UIHostingController
itself calls setNavigationBarHidden
again.
So the reason for this problem is, that the UIHostingControllers
alters the surrounding UINavigationController
's UINavigationBar
.
One easy fix:
Set the Navigation Bar property in the first presented SwiftUI View that is embedded by your UIHostingController
.
var body: some View {
MyOtherView(viewModel: self.viewModel)
.navigationBarHidden(true)
}
This will revert the adjustment SwiftUI and the UIHostingController
are trying to apply to your surrounding UINavigationController
.
As there is no guarantee about the interaction between SwiftUI and UIKit (that it uses underlying UIKit), I would suggest keeping the setNavigationBarHidden
in the surrounding viewDidAppear
together with this modifier, too.
viewWillAppear
if you hide it works but not inviewDidLoad
– Blackburn