-
Notifications
You must be signed in to change notification settings - Fork 3
/
08-Routing.swift
125 lines (113 loc) · 2.94 KB
/
08-Routing.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import SwiftUI
import SwiftUINavigation
private let readMe = """
This case study demonstrates how to power multiple forms of navigation from a single destination \
enum that describes all of the possible destinations one can travel to from this screen.
The screen has four navigation destinations: an alert, a confirmation dialog, a navigation link \
to a count stepper, and a modal sheet to a count stepper. The state for each of these \
destinations is held as associated data of an enum, and bindings to the cases of that enum are \
derived using the tools in this library.
"""
@CasePathable
enum Destination {
case alert(AlertState<AlertAction>)
case confirmationDialog(ConfirmationDialogState<DialogAction>)
case link(Int)
case sheet(Int)
enum AlertAction {
case randomize
case reset
}
enum DialogAction {
case decrement
case increment
}
}
struct Routing: View {
@State var count = 0
@State var destination: Destination?
var body: some View {
Form {
Section {
Text(readMe)
}
Section {
Text("Count: \(count)")
}
Button("Alert") {
destination = .alert(
AlertState {
TextState("Update count?")
} actions: {
ButtonState(action: .send(.randomize)) {
TextState("Randomize")
}
ButtonState(role: .destructive, action: .send(.reset)) {
TextState("Reset")
}
}
)
}
Button("Confirmation dialog") {
destination = .confirmationDialog(
ConfirmationDialogState(titleVisibility: .visible) {
TextState("Update count?")
} actions: {
ButtonState(action: .send(.increment)) {
TextState("Increment")
}
ButtonState(action: .send(.decrement)) {
TextState("Decrement")
}
}
)
}
Button("Link") {
destination = .link(count)
}
Button("Sheet") {
destination = .sheet(count)
}
}
.navigationTitle("Routing")
.alert($destination.alert) { action in
switch action {
case .randomize?:
count = .random(in: 0...1_000)
case .reset?:
count = 0
case nil:
break
}
}
.confirmationDialog($destination.confirmationDialog) { action in
switch action {
case .decrement?:
count -= 1
case .increment?:
count += 1
case nil:
break
}
}
.navigationDestination(item: $destination.link) { $count in
Form {
Stepper("Count: \(count)", value: $count)
}
.navigationTitle("Routing link")
}
.sheet(item: $destination.sheet, id: \.self) { $count in
NavigationStack {
Form {
Stepper("Count: \(count)", value: $count)
}
.navigationTitle("Routing sheet")
}
}
}
}
#Preview {
NavigationStack {
Routing()
}
}