Skip to content

Instantly share code, notes, and snippets.

@bannzai
Last active August 8, 2023 11:30
Show Gist options
  • Save bannzai/344ca0fc441c3df92a6455a4ce2f0301 to your computer and use it in GitHub Desktop.
Save bannzai/344ca0fc441c3df92a6455a4ce2f0301 to your computer and use it in GitHub Desktop.
NavigationStack
class NavigationController: ObservableObject {
@Published var path: NavigationPath = .init()
var destinations: [UUID: () -> any View] = [:]
func push(id: UUID = .init(), @ViewBuilder destination: @escaping () -> some View) {
destinations[id] = destination
path.append(id)
}
func pop() {
path.removeLast()
}
}
@main
struct NavigationDemoApp: App {
@StateObject var navigationController = NavigationController()
var body: some Scene {
WindowGroup {
NavigationStack(path: $navigationController.path) {
ContentView()
.navigationDestination(for: UUID.self) { id in
if let destination = navigationController.destinations[id] {
AnyView(destination())
}
}
}
.environmentObject(navigationController)
}
}
}
// MARK: - Content Views
struct ContentView: View {
@EnvironmentObject var navigationController: NavigationController
var body: some View {
VStack {
Button {
navigationController.push(destination: { ContentView2() })
} label: {
Text("ContentView2")
}
}
.padding()
}
}
struct ContentView2: View {
@EnvironmentObject var navigationController: NavigationController
var body: some View {
VStack {
Button {
navigationController.push(destination: { ContentView3() })
} label: {
Text("ContentView3")
}
}
.padding()
}
}
struct ContentView3: View {
@EnvironmentObject var navigationController: NavigationController
var body: some View {
VStack {
Button {
navigationController.pop()
} label: {
Text("pop")
}
}
.padding()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment