Navigating Between Views with NavigationView
Learn how to perform programmatic navigation between different views in SwiftUI using NavigationView and NavigationLink.
Note:
This tutorial explains one of the easiest ways to handle screen transitions in SwiftUI by wrapping your views in a NavigationView and using NavigationLink to trigger navigation.
Overview
One of the most straightforward ways to enable programmatic transitions between views is to use a NavigationView. Within a NavigationView, you can use a NavigationLink to specify a destination view and a label (which acts like a button) to perform the transition.
Reference:
Using NavigationView and NavigationLink
The basic structure involves wrapping your root view in a NavigationView. Inside, you can place a NavigationLink that points to the destination view you want to navigate to. The label of the NavigationLink is what the user will see and tap.
Here is a complete example with a ContentView and a SecondView:
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
Text("First View")
.font(.largeTitle)
NavigationLink(
destination: SecondView(),
label: {
Text("Go to Second View")
.font(.headline)
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
)
}
.navigationTitle("Main View") // Sets the title in the navigation bar
}
}
}
struct SecondView: View {
var body: some View {
VStack {
Text("You are now on the Second View!")
.font(.largeTitle)
}
.navigationTitle("Second View")
// This provides a consistent back button experience
.navigationBarTitleDisplayMode(.inline)
}
}
Explanation
NavigationView: Acts as a container that provides a navigation stack. Any views inside it can participate in navigation.NavigationLink: This is the trigger. It takes adestinationview and alabel. When the user taps the label, the app navigates to the destination view, pushing it onto the navigation stack..navigationTitle(): This modifier sets the title displayed in the navigation bar for the current view.- Back Button: The
NavigationViewautomatically provides a back button to return to the previous view in the stack.
Note:
NavigationView is a fundamental component for building apps with multiple screens in SwiftUI. It manages the view hierarchy and provides the standard navigation bar look and feel.