Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to hide the navigationBar when embedding swiftUI in UIkit

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.

like image 881
Mike Perhats Avatar asked Nov 05 '19 04:11

Mike Perhats


People also ask

How do I hide navigation controller?

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.

How do I hide the back button in SwiftUI?

The . navigationBarBackButtonHidden(true) will hide the back button.


1 Answers

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())
like image 179
TParizek Avatar answered Sep 21 '22 08:09

TParizek