How to use .navigationDestination with Button in SwiftUI for complex navigation scenarios?
I'm currently working on a settings page in SwiftUI which has approximately 10 buttons. Each of these buttons is not in a ForEach or List due to the need for a custom design, and each button needs to navigate to a different view with distinct variables being passed between them.
In the past, I would have used NavigationLink(destination:label) to achieve this, and while this method still works, I've run into an issue. In one or more of those views, I need to use NavigationLink(isActive), which is now deprecated.
I discovered a potentially better solution using .navigationDestination, but I'm having trouble making it work as expected. For instance, I found that it doesn't programmatically dismiss the view when it's finished being called if it's used in NavigationLink subviews.
Most of the SwiftUI tutorials and resources I've found online demonstrate navigation using List and ForEach with programmatically generated data, but not simple button clicks like in my scenario. And I have watched countless videos and even apple documentation and do not understand anything to do with this type of new navigation.
Could someone explain how to properly use .navigationDestination and its requirements in this context? Specifically, how can I use it with Button(action:label) to navigate to the next view, and how does it behave in NavigationLink subviews?
Any help or guidance on this matter would be greatly appreciated. Here's a simplified example of what I'm trying to accomplish:
First View:
NavigationStack() {
NavigationLink(label: {
Text("Navigate To Second View")
}, destination: {
SecondView()
})
}
Second View:
Button(action: {
isPresented = true //Goes to third view
}) {
Text("Navigate to third view")
}
.navigationDestination(isPresented: $isPresented, destination: ThirdView())
ThirdView:
Button(action: {
isPresented = false //Goes back to second view, however, this seems not to work
}) {
Text("Navigate Back to second view")
}