How to Use NavigationLink in SwiftUI for Navigation
In SwiftUI, use
NavigationLink to create tappable items that navigate to a new view when selected. Wrap your content inside NavigationLink and specify the destination view to enable navigation within a NavigationView.Syntax
The basic syntax of NavigationLink includes a destination view and a label view. The label is what the user taps, and the destination is the view shown after tapping.
It must be used inside a NavigationView to enable navigation.
swift
NavigationView {
NavigationLink(destination: DestinationView()) {
Text("Go to Destination")
}
}Output
A tappable text labeled "Go to Destination" inside a navigation bar; tapping it shows the DestinationView.
Example
This example shows a simple app with a list of items. Tapping an item navigates to a detail view showing the selected item's name.
swift
import SwiftUI struct ContentView: View { let items = ["Apple", "Banana", "Cherry"] var body: some View { NavigationView { List(items, id: \.self) { item in NavigationLink(destination: DetailView(item: item)) { Text(item) } } .navigationTitle("Fruits") } } } struct DetailView: View { let item: String var body: some View { Text("You selected: \(item)") .font(.largeTitle) .padding() } }
Output
A list titled "Fruits" with items Apple, Banana, Cherry; tapping an item shows a new screen with text "You selected: [item]".
Common Pitfalls
- Not wrapping
NavigationLinkinside aNavigationViewwill prevent navigation from working. - Using
NavigationLinkwithout a proper destination view causes runtime errors or blank screens. - Placing multiple
NavigationLinkinside complex views without clear labels can confuse users.
swift
/* Wrong: NavigationLink outside NavigationView */ NavigationLink(destination: Text("Detail")) { Text("Tap me") } /* Right: Wrap in NavigationView */ NavigationView { NavigationLink(destination: Text("Detail")) { Text("Tap me") } }
Output
Wrong: Tapping does nothing or app crashes.
Right: Tapping navigates to "Detail" text view.
Quick Reference
Remember these tips when using NavigationLink:
- Always use inside
NavigationView. - Destination is the view shown after tap.
- Label is the tappable UI element.
- Use descriptive labels for better UX.
Key Takeaways
Wrap NavigationLink inside NavigationView to enable navigation.
NavigationLink requires a destination view and a label view.
Use clear, tappable labels for good user experience.
Without NavigationView, NavigationLink won’t work properly.
Test navigation flows to avoid runtime errors.