Untitled
unknown
plain_text
a year ago
2.8 kB
7
Indexable
import SwiftUI
enum Screen: Hashable {
case second, third, fourth
}
struct ContentView: View {
@State private var path = NavigationPath() // Manages the navigation stack
var body: some View {
NavigationStack(path: $path) {
FirstScreen(path: $path)
.navigationDestination(for: Screen.self) { screen in
switch screen {
case .second:
SecondScreen(path: $path)
case .third:
ThirdScreen(path: $path)
case .fourth:
FourthScreen(path: $path)
}
}
}
}
}
struct FirstScreen: View {
@Binding var path: NavigationPath
var body: some View {
VStack(spacing: 20) {
Text("First Screen")
.font(.largeTitle)
.bold()
Button("Go to Second Screen") {
path.append(Screen.second)
}
.padding()
.foregroundColor(.white)
.background(Color.blue)
.cornerRadius(8)
}
.navigationTitle("First Screen")
}
}
struct SecondScreen: View {
@Binding var path: NavigationPath
var body: some View {
VStack(spacing: 20) {
Text("Second Screen")
.font(.largeTitle)
.bold()
Button("Go to Third Screen") {
path.append(Screen.third)
}
.padding()
.foregroundColor(.white)
.background(Color.green)
.cornerRadius(8)
}
.navigationTitle("Second Screen")
}
}
struct ThirdScreen: View {
@Binding var path: NavigationPath
var body: some View {
VStack(spacing: 20) {
Text("Third Screen")
.font(.largeTitle)
.bold()
Button("Go to Fourth Screen") {
path.append(Screen.fourth)
}
.padding()
.foregroundColor(.white)
.background(Color.orange)
.cornerRadius(8)
}
.navigationTitle("Third Screen")
}
}
struct FourthScreen: View {
@Binding var path: NavigationPath
var body: some View {
VStack(spacing: 20) {
Text("Fourth Screen")
.font(.largeTitle)
.bold()
Text("You are on the last screen!")
Button("Go Back to First Screen") {
path.removeLast(path.count) // Clears the navigation stack
}
.padding()
.foregroundColor(.white)
.background(Color.red)
.cornerRadius(8)
}
.navigationTitle("Fourth Screen")
}
}
Editor is loading...
Leave a Comment