SwiftUI:允许导航栏仅出现在 main/first 页面上

SwiftUI: allow navigation bar to appear ONLY on the main/first page

我写了一个简单格式的代码,显示如果允许导航栏出现在 first/main 页面上,通过使用 .navigationBarTitle(...),该页面的子视图将有导航酒吧.

主视图:

struct ContentView: View {
    var body: some View {
        NavigationView{
            VStack{
                NavigationLink(destination: View01()){
                    Text("To view 1")
                }
            }
            .navigationBarTitle("Front Page", displayMode: .inline) //removable, but needed for the first page's bar
        }
    }
}

主视图的子视图:

struct View01: View {
    var body: some View {
        VStack{
            EmptyView()
        }
        .navigationBarBackButtonHidden(true) //the back button is gone 
        .navigationBarHidden(true) //this has no effect here
    }
}

当我从主代码中删除 .navigationBarTitle(...) 时,导航栏从所有视图中消失。但是,如果我把它放回去并在子视图代码中使用 .navigationBarHidden(true),导航栏仍保留在这里。

我正在寻找任何解决方案,让我的导航栏只出现在 first/front/main 页面上,而其他 pages/child 页面没有导航栏。

如果要使用pushpop, 请试试这个方法:

struct ParentView: View {
    @State var navigationBarIsHidden: Bool = false
    @State private var showDetail = false
    var body: some View {
        NavigationView {
            ZStack {
                Color.red
                NavigationLink("show child view", destination: ChildView(navigationBarIsHidden: $navigationBarIsHidden, showSelf: $showDetail), isActive: $showDetail)
            }
            .navigationBarTitle("title", displayMode: .inline)
            .navigationBarHidden(navigationBarIsHidden)
            .onAppear {
                self.navigationBarIsHidden = false
            }
        }
    }
}

ChildView.swift

struct ChildView: View {
    @Binding var navigationBarIsHidden: Bool
    @Binding var showSelf: Bool
    var body: some View {
        ZStack {
            Color.green
            Text("ChildView").onTapGesture {
                self.navigationBarIsHidden = false
                self.showSelf = false
            }
        }
        .onAppear {
            self.navigationBarIsHidden = true
        }
    }
}