Search code examples
swiftswiftuiswiftui-navigationlink

Hide navigation bar in all the views, swiftUI


Currently I am working on SwiftUI project. I want to hide the build-in navbar. For this purpose I have to add these lines,

.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)

to each of view before pushing it into navigation controller in SwiftUI.

   NavigationLink(destination:
                    ForgotPasswordView()
                              .navigationBarBackButtonHidden(true)
                              .navigationBarHidden(true)
    
    ) {
            Text("Forgot Password?")
                .foregroundColor(.white)
    }

Same will be done for LoginView

NavigationLink(destination:
                        LoginView()
                                  .navigationBarBackButtonHidden(true)
                                  .navigationBarHidden(true)
        
        ) {
                Text("Login")
                    .foregroundColor(.white)
        }

So I need any generic method like we did in storyboard, hide it from root view and no child will have the navbar on top.


Solution

  • You can create a custom modifier to hide the navigation bar like this:

    struct HideNavBar : ViewModifier {
        
        func body(content: Content) -> some View {
            content
                .navigationBarTitle("")
                .navigationBarHidden(true)
                .navigationBarBackButtonHidden(true)
        }
    }
    
    extension View {
        var hideNavigationBar: some View {
            modifier(HideNavBar())
        }
    }
    

    And use it like this:

    NavigationLink(destination:
                        ForgotPasswordView()
                                  .hideNavigationBar
        
        ) {
                Text("Forgot Password?")
                    .foregroundColor(.white)
        }