Skip to content

Instantly share code, notes, and snippets.

@pitt500
Last active July 13, 2022 12:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pitt500/c52040dd1b250539db8c9116d2cddda0 to your computer and use it in GitHub Desktop.
Save pitt500/c52040dd1b250539db8c9116d2cddda0 to your computer and use it in GitHub Desktop.
import SwiftUI
struct ContentView: View {
@State private var path: [Fruit] = []
var body: some View {
NavigationStack(path: $path) {
List {
NavigationLink(Fruit.apple.name, value: Fruit.apple)
NavigationLink(Fruit.orange.name, value: Fruit.orange)
NavigationLink(Fruit.banana.name, value: Fruit.banana)
}
.navigationTitle("Fruits")
.navigationDestination(for: Fruit.self) { fruit in
FruitView(fruit: fruit) { nextFruit in
NavigationLink(value: nextFruit) {
Text("Next is \(nextFruit.name)")
.foregroundColor(.accentColor)
}
.buttonStyle(.plain)
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
overrideNavigation()
} label: {
Text("Override")
}
}
}
}
}
}
func overrideNavigation() {
path = [.orange, .orange, .banana, .banana]
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
enum Fruit: String, Hashable, CaseIterable {
case banana = "🍌"
case orange = "🍊"
case peach = "🍑"
case apple = "🍎"
static var random: Self {
Self.allCases.randomElement()!
}
var color: Color {
switch self {
case .banana:
return .yellow
case .orange:
return .orange
case .peach:
return .pink
case .apple:
return .red
}
}
var name: String {
switch self {
case .banana:
return "Banana"
case .orange:
return "Orange"
case .peach:
return "Peach"
case .apple:
return "Apple"
}
}
}
extension Fruit: Identifiable {
var id: String { self.rawValue }
}
struct FruitView<Link: View>: View {
let fruit: Fruit
var nextLink: ((Fruit) -> Link)? = nil
var body: some View {
ZStack {
fruit.color.opacity(0.2).ignoresSafeArea(.all)
VStack {
Text(fruit.rawValue)
.font(.system(size: 100))
.padding()
nextLink?(Fruit.random)
}
}
.navigationTitle("\(fruit.name)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment