Stefano Toppi
Stefano Toppi

Reputation: 656

SwiftUI Navigation Multiple back button

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

Upvotes: 18

Views: 6783

Answers (2)

cristian9804
cristian9804

Reputation: 93

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

Upvotes: 1

Gene Z. Ragan
Gene Z. Ragan

Reputation: 2863

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.

Upvotes: 31

Related Questions