swiftuinavigationbarnavigationlink

SwiftUI - Using Navigation View and Sheets correctly


Having issues with a NavigationView and Sheet. I have the below flow: - ContentView: Has button that opens ContentView2 sheet - ContentView2: Has NavigationLink with header that goes to ContentView3 - ContentView3: Has NavigationLink, no header, that directs users to ContentView2

However, when I set up the above flow, I end up getting stacked headers when users go back and forth between ContentView2 and ContentView3. How would I prevent this and only have 1 header when users go back and forth between the two views? Thanks!

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


Solution

  • You need only one NavigationView in root, so here is corrected components

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