\n","author":{"@type":"Person","name":"squarehippo10"},"upvoteCount":1,"answerCount":2,"acceptedAnswer":{"@type":"Answer","text":"
You should not create NavigationLink(destination: ViewA())
because it is not back it creates a new ViewA. Once you navigate to ViewB, the back button will be create for you automatically.
struct ViewA: View {\n var body: some View {\n NavigationView{\n NavigationLink(destination: ViewB()) {\n Text("ViewB")\n }\n }\n .navigationBarTitle("ViewA")\n }\n}\n\nstruct ViewB: View {\n var body: some View {\n Text("ViewB Pure Content")\n .navigationBarTitle("ViewB")\n }\n}\n
\n","author":{"@type":"Person","name":"Asperi"},"upvoteCount":1}}}Reputation: 1945
In the code below, if I use the links to go back and forth between views A and B, I will end up with nested views as shown in the image. The only way I've found to avoid nesting is to never link to a view where a NavigationView is declared - as it is in ViewA below. My question...is there any way to go back to ViewA without the views nesting?
struct ViewA: View {
var body: some View {
NavigationView{
NavigationLink(destination: ViewB()) {
Text("ViewB")
}
}
.navigationBarTitle("ViewA")
}
}
struct ViewB: View {
var body: some View {
NavigationLink(destination: ViewA()) {
Text("ViewA")
}
.navigationBarTitle("ViewB")
}
}
Upvotes: 1
Views: 508
Reputation: 258591
You should not create NavigationLink(destination: ViewA())
because it is not back it creates a new ViewA. Once you navigate to ViewB, the back button will be create for you automatically.
struct ViewA: View {
var body: some View {
NavigationView{
NavigationLink(destination: ViewB()) {
Text("ViewB")
}
}
.navigationBarTitle("ViewA")
}
}
struct ViewB: View {
var body: some View {
Text("ViewB Pure Content")
.navigationBarTitle("ViewB")
}
}
Upvotes: 1
Reputation: 51
You are nesting views because every time you click ViewA/ViewB it creates a new view object. You can add
@Environment(\.presentationMode) var presentationMode
and call
presentationMode.wrappedValue.dismiss()
when the view button gets pressed you dismiss it.
Upvotes: 0