In SwiftUI, navigation is typically handled using the NavigationView
and related components. Here’s a basic guide on how to perform navigation in SwiftUI:
Basic Navigation with NavigationLink:
- Using NavigationView:
- Start by embedding your root view in a
NavigationView
.
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
// Your content here
}
}
}
2. Creating NavigationLinks:
- Inside the
NavigationView
, use theNavigationLink
to create links to other views.
NavigationLink("Go to Detail View", destination: DetailView())
3. Creating the Destination View:
- Create the destination view (
DetailView
in this example).
struct DetailView: View {
var body: some View {
Text("This is the Detail View")
}
}
4. Putting it All Together:
- Your complete view with navigation links might look like this:
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
NavigationLink("Go to Detail View", destination: DetailView())
}
.navigationTitle("Main View")
}
}
}
struct DetailView: View {
var body: some View {
Text("This is the Detail View")
.navigationTitle("Detail View")
}
}
Passing Data with NavigationLink:
- Using
NavigationLink
withNavigationLinkDestination
:
To pass data to the destination view, useNavigationLink(destination:label:)
with aNavigationLinkDestination
closure.
NavigationLink(
destination: DetailView(data: "Hello from Main View"),
label: {
Text("Go to Detail View with Data")
}
)
2. Receiving Data in Destination View:
In the destination view, define a property to receive the data.
struct DetailView: View {
var data: String
var body: some View {
Text("Received Data: \(data)")
.navigationTitle("Detail View")
}
}
Programmatic Navigation:
- Using
NavigationLink
withisActive
:
For programmatic navigation, use a@State
variable to control the navigation.
@State private var isDetailViewActive = false
NavigationLink(
destination: DetailView(),
isActive: $isDetailViewActive,
label: {
Text("Go to Detail View Programmatically")
}
)
Triggering Navigation Programmatically:
- Change the state variable to trigger navigation.
Button("Programmatic Navigation") {
isDetailViewActive = true
}
Complete Example:
struct ContentView: View {
@State private var isDetailViewActive = false
var body: some View {
NavigationView {
VStack {
NavigationLink(
destination: DetailView(),
isActive: $isDetailViewActive,
label: {
Text("Go to Detail View Programmatically")
}
)
Button("Programmatic Navigation") {
isDetailViewActive = true
}
}
.navigationTitle("Main View")
}
}
}
struct DetailView: View {
var body: some View {
Text("This is the Detail View")
.navigationTitle("Detail View")
}
}
These examples cover the basics of navigation in SwiftUI. Depending on your app’s complexity, you may explore other navigation-related components such as NavigationViewStyle
, NavigationViewToolbar
, and navigation stacks for more advanced navigation patterns