
Here is an example of a SwiftUI app that demonstrates navigation between multiple views using NavigationView
and NavigationLink
. This example will help you understand how to structure navigation hierarchies in SwiftUI:
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: DetailView()) {
Text("Go to Detail View")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
}
NavigationLink(destination: SettingsView()) {
Text("Go to Settings View")
.padding()
.background(Color.green)
.foregroundColor(.white)
.cornerRadius(8)
}
}
.navigationBarTitle("Home")
}
}
}
struct DetailView: View {
var body: some View {
VStack {
Text("This is the Detail View")
.font(.largeTitle)
.padding()
NavigationLink(destination: MoreDetailView()) {
Text("Go to More Detail View")
.padding()
.background(Color.orange)
.foregroundColor(.white)
.cornerRadius(8)
}
}
.navigationBarTitle("Detail")
}
}
struct MoreDetailView: View {
var body: some View {
Text("This is the More Detail View")
.font(.largeTitle)
.padding()
.navigationBarTitle("More Detail")
}
}
struct SettingsView: View {
var body: some View {
Text("This is the Settings View")
.font(.largeTitle)
.padding()
.navigationBarTitle("Settings")
}
}
@main
struct MultiViewApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}

Explanation:
- ContentView Struct:
- Wrapped in a
NavigationView
to provide a navigation context. - Contains
NavigationLink
views to navigate toDetailView
andSettingsView
. - Each
NavigationLink
has a destination and a label.
- Wrapped in a
- DetailView Struct:
- A simple view with text and a
NavigationLink
toMoreDetailView
. - The navigation bar title is set to “Detail”.
- A simple view with text and a
- MoreDetailView Struct:
- A view with text and a navigation bar title “More Detail”.
- SettingsView Struct:
- A view with text and a navigation bar title “Settings”.
- MultiViewApp Struct:
- Sets up the main window of the app with
ContentView
as its root view.
- Sets up the main window of the app with
How to Use:
- Copy the code into a new SwiftUI project in Xcode.
- Run the project on a simulator or device to see the navigation in action.
- Tap the buttons to navigate between the different views.
This example demonstrates how to create a navigation hierarchy in SwiftUI using NavigationView
and NavigationLink
, enabling you to build apps with multiple views and seamless navigation.