I am trying to hide the navigationBar
when putting some swiftUI inside of a UIKit
viewController
as such:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setNavigationBarHidden(true, animated: animated)
But it does not go away. When I take away the swiftUI, however it works. Does anyone know how to solve this?
Edit:
I am instantiating a view like this
let controller = UIHostingController(rootView:view())
where view is the swiftUI and then adding this to the UIView() as you would any UIKit element.
Touch “Settings” -> “Display” -> “Navigation bar” -> “Buttons” -> “Button layout”. Choose the pattern in “Hide navigation bar” -> When the app opens, the navigation bar will be automatically hidden and you can swipe up from the bottom corner of the screen to show it.
The . navigationBarBackButtonHidden(true) will hide the back button.
UIHostingViewController respects the navigationBarHidden
value of your SwiftUI view. You can either call .navigationBarHidden(true)
at the end of your SwiftUI view, or you can use the custom UIHostingController subclass shown in the example below.
Solution:
import SwiftUI
import UIKit
class YourHostingController <Content>: UIHostingController<AnyView> where Content : View {
public init(shouldShowNavigationBar: Bool, rootView: Content) {
super.init(rootView: AnyView(rootView.navigationBarHidden(!shouldShowNavigationBar)))
}
@objc required dynamic init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Example of usage:
let hostVc = YourHostingController(shouldShowNavigationBar: false, rootView: YourSwiftUIView())
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