5

I have looked into many solutions but none of them works. My app navigation flow is

  1. ViewController (UIKit) - pushes to SwiftUI view
  2. This SwiftUI view shows the back bar button for a fraction of seconds and then gets hidden.

Here is my code:

struct FirstSwiftUIView: View {

var body: some View {

  VStack {
    Text("First SwiftUi View")
    NavigationLink {
      SecondSwiftUIView()
    } label: {
      Text("Next View")
    }
  }
  .navigationBarBackButtonHidden(true)
  .navigationBarTitle("")
}

}

Bhuvan Bhatt
  • 3,276
  • 2
  • 18
  • 23

3 Answers3

10

I have found the fix. The back button can be hidden from UIHostingController before coming to SwiftUI from UIKit.

let firstSwiftUI = UIHostingController(rootView: FirstSwiftUIView())
firstSwiftUI.navigationItem.hidesBackButton = true
navigationController?.pushViewController(firstSwiftUI, animated: true)
John Gorenfeld
  • 2,015
  • 1
  • 18
  • 27
Bhuvan Bhatt
  • 3,276
  • 2
  • 18
  • 23
1

You can use this trick:

final class CommonHostingController<Content: View>: UIHostingController<Content> {
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: false)
        navigationController?.setNavigationBarHidden(false, animated: animated)
    }
}

Your navigation bar of SwiftUI view will show immediately, but navigation bar of your UIKit viewController will hide during push animation.

Looks better.

vouliont
  • 11
  • 2
0
  • wrap the view in a NavigationView. (maybe you did this in the App strucutre)

  • use the .navigationBarBackButtonHidden(true) in the destination view – because there you want to hide the back button.

    struct ContentView: View {

      var body: some View {
    
          NavigationView {
              VStack {
                  Text("First SwiftUi View")
                  NavigationLink {
    
                      // your destination view
                      Text("Destination")
                          .navigationBarBackButtonHidden(true)
    
                  } label: {
                      Text("Next View")
                  }
              }
              .navigationBarTitle("")
          }
      }
    

    }

ChrisR
  • 9,523
  • 1
  • 8
  • 26
  • The view from which I am coming to FirstSwiftUIView is in UIKit (a ViewController) and it already has a UINavigationController. So adding NavigationView again in SwiftUI will create two navigation bar on the top. – Bhuvan Bhatt Feb 02 '22 at 09:24
  • then just delete my additional `NavigationView` – the important point is, that the `.navigationBarBackButtonHidden(true)` is on the inner view. – ChrisR Feb 02 '22 at 09:29
  • Actually this works fine if first and second view are SwiftUI. But not when I navigate from UIKit to SwiftUI. – Bhuvan Bhatt Feb 02 '22 at 09:47