在SwiftUI中存在多个导航视图时隐藏导航栏

时间:2020-06-30 11:52:32

标签: swiftui swiftui-navigationlink

在有多个导航视图的情况下,我无法隐藏导航栏。我希望导航栏出现在第一个和第二个屏幕上,而不要出现在第三个屏幕上。

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

我尝试使用上面的代码在第三屏上隐藏导航栏,但是它不起作用:(

It doesn't hide the navigation bar

1 个答案:

答案 0 :(得分:1)

如果您想在第三视图完全隐藏导航栏,可以采用以下方法。 (注意:顺便说一句,在一个视图层次结构中必须只有一个NavigationView,因此在ThirdView中不需要另一个

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