2
votes

I am having trouble hiding the navigation bar in case of multiple navigation views. I want navigation bars to be present on first and second screen but not on the third one.

struct FirstView: View {

    init() {
        UINavigationBar.appearance().backgroundColor = UIColor.green
    }

    var body: some View {
        NavigationView {
                NavigationLink(destination: SecondView()) {
                    Text("Second View")
            }.navigationBarTitle("First View")
        }
    }
}
 
// Second View

struct SecondView: View {
    var body: some View {
        NavigationLink(destination: ThirdView()) {
            Text("Third View")
        }
    }
}

// Third View 

struct ThirdView: View {

    var body: some View {
        
            Text("Welcome")
            .navigationBarTitle("")
            .navigationBarHidden(true)
        
    }
}

I tried hiding the navigation bar on third screen with the above code, but it doesn't work :(

It doesn't hide the navigation bar

1
You should only have one NavigationView per navigation stack.pawello2222

1 Answers

1
votes

If you want to hide navigation bar completely at third view here is possible approach. (Note: btw in one view hierarchy there must be only one NavigationView, so another one in ThirdView is not needed)

Tested with Xcode 11.4 / iOS 13.4

class HideBarViewModel: ObservableObject {
    @Published var isHidden = false
}

struct FirstView: View {
    @ObservedObject var vm = HideBarViewModel()
    init() {
        UINavigationBar.appearance().backgroundColor = UIColor.green
    }

    var body: some View {
        NavigationView {
                NavigationLink(destination: SecondView()) {
                    Text("Second View")
            }.navigationBarTitle("First View")
            .navigationBarHidden(vm.isHidden)
        }.environmentObject(vm)
    }
}

// Second View

struct SecondView: View {
    var body: some View {
        NavigationLink(destination: ThirdView()) {
            Text("Third View")
        }
    }
}

// Third View

struct ThirdView: View {
    @EnvironmentObject var vm: HideBarViewModel
    var body: some View {
        Text("Welcome")
            .onAppear {
                self.vm.isHidden = true
            }
    }
}