SwiftUI - 正确使用导航视图和表格

SwiftUI - Using Navigation View and Sheets correctly

NavigationView 和 Sheet 有问题。我有以下流程: - ContentView:具有打开 ContentView2 的按钮 sheet - ContentView2:具有 header 的 NavigationLink 转到 ContentView3 - ContentView3:有 NavigationLink,没有 header,将用户定向到 ContentView2

但是,当我设置上述流程时,当用户在 ContentView2 和 ContentView3 之间来回切换时,我最终会堆叠 headers。当用户在两个视图之间来回切换时,我将如何防止这种情况并且只有 1 header?谢谢!

struct ContentView: View {
    @State var showSheet = false

    var body: some View {
        Button("Click"){
            self.showSheet.toggle()
        }
        .sheet(isPresented: $showSheet) {
            ContentView2()
        }
    }
}


struct ContentView2: View {
    var body: some View {
        NavigationView {
            NavigationLink(destination: ContentView3()){
                Text("Click Here")
            }
            .navigationBarTitle("Bar Title", displayMode: .inline)
        }
    }
}

struct ContentView3: View {
    var body: some View {
        NavigationLink(destination: ContentView2()){
            Text("Click Here")
        }
    }
}

你只需要一个 NavigationView 在 root 中,所以这里是更正的组件

struct ContentView: View {
    @State var showSheet = false

    var body: some View {
        Button("Click"){
            self.showSheet.toggle()
        }
        .sheet(isPresented: $showSheet) {
           NavigationView {    // only here !!
            ContentView2()
           }
        }
    }
}


struct ContentView2: View {
    var body: some View {
         NavigationLink(destination: ContentView3()){
             Text("Click Here")
         }
         .navigationBarTitle("Bar Title", displayMode: .inline)
    }
}