Home > Software design >  SwiftUI - Navigation bar back button appears for a fraction of second
SwiftUI - Navigation bar back button appears for a fraction of second

Time:02-02

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("")
}

}

CodePudding user response:

  • 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("")
          }
      }
    

    }

CodePudding user response:

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

let firstSwiftUI = UIHostingController(rootView: FirstSwiftUIView())
firstSwiftUI.navigationItem.hidesBackButton = true
navigationController?.pushViewController(firstSwiftUI, animated: true)
  •  Tags:  
  • Related