Search code examples
swiftuinavigation

How do I change my code from using NavigationView to NavigationStack?


I'm new to swiftui and I need help transitioning my code from using NavigationView to NavigationStack. The reason I need to do this is to be able to let the user go back to the root view of the stack(which is my content view file). Also navigationview is deprecated in iOS 16 so I think its better I just learn how to use it now rather than later. I've attached a picture of my code with the current errors. Please let me know if I need to post any additional information that is needed to help me.

My current code with the errors:

enter image description here

I'm currently using navigation view which works but doesn't give the user the ability to go back to the root view. So I need to update my code to use NavigatinView instead but I'm not sure how to update my code to get rid of the errors that show when I change it to navigationstack.


Solution

  • When you upgrade to NavigationStack you need to use the new value-based NavigationLink and .navigationDestination, e.g.

    List(exercises) { exercise in
        NavigationLink(exercise.title, value: exercise)
    }
    .navigationDestination(for: ExerciseView.self) { exercise in
        ExerciseView(exercise: exercise)
    }
    

    Note: you can have multiple .navigationDestination and they be positioned anywhere in the View hierarchy below the NavigationStack.