Search code examples
swiftswiftuiswiftui-navigationlink

Navigation Link in bar Items goes back to top of NavigationView


struct Testing: View {

    var body: some View {
        NavigationView{
            VStack {
                Text("View 1")
                Text("View 1.3")
            
                NavigationLink(destination: TestView(),
                                    label: {
                                        Text("View 1 navigation")
                                    })
            }
        }
    }
}

struct TestView: View {

    var body: some View {
            VStack {
                Text("View 2")
            }
            .navigationBarItems(trailing:NavigationLink(
                                    destination: Text("View 3"),
                                    label: {
                                        Text("Navigate")
                                     }))
    }
}

When clicking the NavigationLink inside of TestViews navigationBarItems it navigates to View 3. When I click the back button it does not go back to TestView it goes all the way back to Testing instead.

How do I make it go back to the previous view instead of the first view?

I am using Xcode 12.


Solution

  • Put navigation link into body of navigation view (bar is not in navigation view)

    So here is possible approach

    struct TestView: View {
        @State private var isActive = false
    
        var body: some View {
                VStack {
                    Text("View 2")
                }
                .background(
                   NavigationLink(destination: Text("View 3"), isActive: $isActive,
                    label: { EmptyView() })
                )
                .navigationBarItems(trailing:
                   Button("Navigate", action: { self.isActive = true }))
        }
    }