Hiding Navigation Bar in case of multiple Navigation Views in SwiftUI

前提是你 提交于 2021-02-10 07:09:46

问题


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 :(


回答1:


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
            }
    }
}


来源:https://stackoverflow.com/questions/62656831/hiding-navigation-bar-in-case-of-multiple-navigation-views-in-swiftui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!