Skip to content

Instantly share code, notes, and snippets.

@Drag0ndust
Created July 25, 2022 06:28
Show Gist options
  • Save Drag0ndust/725154e0a2b7af5a805adf73f1885875 to your computer and use it in GitHub Desktop.
Save Drag0ndust/725154e0a2b7af5a805adf73f1885875 to your computer and use it in GitHub Desktop.
NavigationLink example (Twitch Live Coding "arconsis")
//
// ContentView.swift
// iOS16
//
// Created by arconsis on 22.07.22.
//
import SwiftUI
enum Route {
case first, second, third
}
class Router: ObservableObject {
@Published var navPath = NavigationPath()
func popToRoot() {
navPath = NavigationPath()
}
func goBack() {
navPath.removeLast()
}
func go(to route: Route) {
navPath.append(route)
}
}
struct ContentView: View {
@StateObject private var router: Router = Router()
var body: some View {
NavigationStack(path: $router.navPath) {
Button(action: {
router.go(to: .first)
}, label: {
Text("Go to First View")
})
.navigationDestination(for: Route.self, destination: view(for:))
}
}
@ViewBuilder
func view(for route: Route) -> some View {
switch route {
case .first:
FirstView()
case .second:
SecondView()
case .third:
ThirdView()
.environmentObject(router)
}
}
}
struct FirstView: View {
var body: some View {
ZStack {
Color.red
.ignoresSafeArea()
NavigationLink(value: Route.second) {
Text("Go to Second View")
}
}
.navigationTitle(Text("First View"))
}
}
struct SecondView: View {
var body: some View {
ZStack {
Color.orange
.ignoresSafeArea()
.navigationTitle(Text("Second View"))
NavigationLink(value: Route.third) {
Text("Go to Third View")
}
}
}
}
struct ThirdView: View {
@EnvironmentObject private var router: Router
var body: some View {
ZStack {
Color.yellow
.ignoresSafeArea()
.navigationTitle(Text("Third View"))
VStack {
Button {
router.goBack()
} label: {
Text("Go back")
}
Button {
router.popToRoot()
} label: {
Text("Pop to root")
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment