Search code examples
swiftuiswiftui-navigationlinkswiftui-navigationview

SwiftUi Navigation link to Same View always gets added as a subview


I'm trying to navigate to the same view with different data from a navigation link on the current view.

However, I see that the new view when navigated to gets added as a child view below the first view. Like the image shown below. Is this expected?

enter image description here enter image description here

The code looks something like this.

View1 is a

VStack {
   HStack {
      Text("")
   }
   Divider()
   HStack {
      Text("some text")
   }
   NavigationView {
      VStack {
          NavigationLink(destination: View1(data: newData) {
              Text("option")
          }
      }
   }
}

Solution

  • Based on your comment, you seem to misunderstand what NavigationView actually does. Think of it as a UINavigationController (because it essentially is one) and NavigationLink as a view with a Touch Up Inside storyboard segue action.

    As Asperi said, NavigationView should be the parent view:

    var body: some View {
        NavigationView {
            [...]
    
            NavigationLink(destination: View1(data: newData) {
                [...]
            }
        }
    }