NavigationLink is a view in SwiftUI that allows you to control navigation and present a new destination view. It is commonly used in conjunction with a NavigationView to create a navigation hierarchy. In this tutorial, we will explore how to use NavigationLink in SwiftUI with examples.
Basic Usage of NavigationLink
To use NavigationLink, you need to wrap your views in a NavigationView. Here’s a basic example:
struct ContentView: View { var body: some View { NavigationView { NavigationLink(destination: DetailView()) { Text("Tap Me") } } } } struct DetailView: View { var body: some View { Text("Hello, I'm a Detail View") } }
In this example, when the user taps on the “Tap Me” text, the DetailView will be presented. The NavigationView provides the navigation hierarchy, and the NavigationLink specifies the destination view.
Using NavigationLink in a List
One common use case for NavigationLink is within a List. Here’s an example:
struct ContentView: View { var body: some View { NavigationView { List(0..<5) { index in NavigationLink(destination: DetailView()) { Text("Row \(index)") } } } } } struct DetailView: View { var body: some View { Text("Hello, I'm a Detail View") } }
In this example, a list is created with five rows, and each row is wrapped in a NavigationLink. When a row is tapped, the DetailView will be presented.
Programmatically Triggering NavigationLink
You can also programmatically trigger a NavigationLink by using a selection property. Here's an example:
struct ContentView: View { @State private var selection: String? = nil var body: some View { NavigationView { VStack { NavigationLink(destination: Text("View A"), tag: "A", selection: $selection) { EmptyView() } NavigationLink(destination: Text("View B"), tag: "B", selection: $selection) { EmptyView() } Button("Tap to show A") { selection = "A" } Button("Tap to show B") { selection = "B" } } .navigationTitle("Navigation") } } }
In this example, we have two NavigationLinks with different tags. When the corresponding button is tapped, the selection property is updated, and the respective destination view is presented.
Conclusion
In this tutorial, we explored the usage of NavigationLink in SwiftUI. We learned how to use it to navigate to a new destination view, how to use it within a List, and how to programmatically trigger navigation. NavigationLink is a powerful tool for creating navigation hierarchies in SwiftUI.
I hope this tutorial helps you understand how to use NavigationLink in SwiftUI. If you have any further questions, feel free to ask!