Most applications consist of more than one screen.
To move between screens, iOS uses a hierarchical navigation system where new views slide in from the right.
SwiftUI makes this process incredibly simple using the NavigationStack and NavigationLink views.
To enable navigation, your top-most view must be wrapped inside a NavigationStack.
This container manages the stack of views being displayed and automatically provides the top navigation bar and back buttons.
import SwiftUIstruct HomeView: View { var body: some View { NavigationStack { Text("Welcome Home") .navigationTitle("Home Page") } } }
Notice how the .navigationTitle() modifier is placed inside the stack, on the view itself!
To actually trigger a transition to a new screen, you use a NavigationLink.
A NavigationLink acts like a button. You provide it a destination (the view to show) and a label (what the button looks like).
struct HomeView: View {
var body: some View {
NavigationStack {
VStack {
NavigationLink(destination: DetailView()) {
Text("Go to Details")
.foregroundColor(.white)
.padding()
.background(Color.blue)
.cornerRadius(8)
}
}
.navigationTitle("Home")
}
}
}
struct DetailView: View {
var body: some View {
Text("This is the detail screen!")
.navigationTitle("Details")
}
}
When tapped, the DetailView automatically slides in, complete with a functional "Back" button!
Passing data in SwiftUI is as simple as initializing a property.
If your DetailView has a property like var username: String, you simply pass it in the NavigationLink!
NavigationLink(destination: DetailView(username: "Akash"))
This seamless data passing is a huge upgrade over older UIKit paradigms.
Which view must wrap your content to enable hierarchical push/pop screen transitions?