SwiftUI-正确使用导航视图和图纸

时间:2020-06-20 04:58:02

标签: swiftui navigationbar navigationlink

NavigationView和Sheet存在问题。我有以下流程: -ContentView:具有打开ContentView2工作表的按钮 -ContentView2:具有带有转到ContentView3的标头的NavigationLink -ContentView3:具有NavigationLink,无标题,可将用户定向到ContentView2

但是,当我设置以上流程时,当用户在ContentView2和ContentView3之间来回移动时,最终会得到堆积的标题。当用户在两个视图之间来回切换时,如何防止出现这种情况并且只有1个标头呢?谢谢!

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

Screenshot of Issue

1 个答案:

答案 0 :(得分:1)

您只需要一个NavigationView根目录,因此这里的组件已更正

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