SwiftUI Navigation Multiple back button
Asked Answered
S

2

18

When I push more than one view, multiple back buttons are visible in the navigation bar.

struct ContentView: View {
    var body: some View {
        NavigationView {
             NavigationLink(destination:SecView()) {
                   Text("Primo")
               }
        }
    }
}

struct SecView: View {
    var body: some View {
        NavigationView {
             NavigationLink(destination:TerView()) {
                   Text("Secondo")
               }
        }
    }
}

struct TerView: View {
    var body: some View {
        Text("Hello World!")
    }
}

I would like to have only one back button per view.

Here is a screenshot of the problem.

enter image description here

Sarabia answered 20/10, 2019 at 22:6 Comment(0)
L
31

There should only be a single NavigationView at the root of your navigation stack.

Remove the NavigationView block from SecView and you will then have a single navigation bar owned by ContentView.

Lauritz answered 20/10, 2019 at 22:30 Comment(0)
L
1

as Gene said, there should only be a single NavigationView at the root of you navigation stack. This means that the next time you need to navigate to a page in a different View, you will add a NavigationLink but not wrap it in a NavigationView. So in the code that you initially posted, you need to remove the NavigationView from your SecView View but still keep the NavigationLink. See the code below:

struct ContentView: View {
    var body: some View {
        NavigationView {
             NavigationLink(destination:SecView()) {
               Text("Primo")
             }
        }
    }
}


struct SecView: View {
    var body: some View {
         NavigationLink(destination:TerView()) {
               Text("Secondo")
           }
    }
}

struct TerView: View {
    var body: some View {
        Text("Hello World!")
    }
}
Louella answered 11/1, 2023 at 20:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.