Navigation Link in bar Items goes back to top of NavigationView

核能气质少年 提交于 2021-01-28 01:57:23

问题


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.


回答1:


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


来源:https://stackoverflow.com/questions/64032314/navigation-link-in-bar-items-goes-back-to-top-of-navigationview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!