1
-
2
1
import SwiftUI
3
-
4
- /**
2
+ /*
5
3
A stateful view in a closure or function-based component instead of a struct-based view.
6
4
The stateful view allows for building content with state, and holds the state of the component.
5
+
6
+ ```swift
7
+ struct ComponentState: Equatable {
8
+ var a = "1"
9
+ var b = "2"
10
+ var c = "3"
11
+ }
12
+
13
+ var body: some View {
14
+ VStack {
15
+ LocalState(
16
+ initial: ComponentState(),
17
+ onChange: { print($0) }
18
+ ) { state in
19
+ TextField("A", text: state.a)
20
+ TextField("B", text: state.b)
21
+ TextField("C", text: state.c)
22
+ }
23
+ }
24
+ }
25
+ ```
7
26
*/
8
- public struct LocalState < State, Content: View > : View {
27
+ public struct LocalState < State: Equatable , Content: View > : View {
9
28
10
29
@SwiftUI . State var state : State
11
30
12
31
private let content : ( Binding < State > ) -> Content
13
32
33
+ private let onChange : ( State ) -> Void
34
+
14
35
public init (
15
36
initial: State ,
37
+ onChange: @escaping ( State ) -> Void = { _ in } ,
16
38
@ViewBuilder content: @escaping ( Binding < State > ) -> Content
17
39
) {
40
+ self . onChange = onChange
18
41
self . _state = . init( initialValue: initial)
19
42
self . content = content
20
43
}
21
44
22
45
public var body : some View {
23
46
content ( $state)
47
+ . onChange ( of: state) { newValue in
48
+ onChange ( newValue)
49
+ }
24
50
}
25
51
26
52
}
@@ -34,6 +60,8 @@ struct BookState: View, PreviewProvider {
34
60
35
61
static var previews : some View {
36
62
Self ( )
63
+ Content3 ( )
64
+ . previewDisplayName ( " Binding " )
37
65
}
38
66
39
67
private struct Content : View {
@@ -90,6 +118,28 @@ struct BookState: View, PreviewProvider {
90
118
}
91
119
}
92
120
121
+ private struct Content3 : View {
122
+
123
+ struct ComponentState : Equatable {
124
+ var a = " 1 "
125
+ var b = " 2 "
126
+ var c = " 3 "
127
+ }
128
+
129
+ var body : some View {
130
+ VStack {
131
+ LocalState (
132
+ initial: ComponentState ( ) ,
133
+ onChange: { print ( $0) }
134
+ ) { state in
135
+ TextField ( " A " , text: state. a)
136
+ TextField ( " B " , text: state. b)
137
+ TextField ( " C " , text: state. c)
138
+ }
139
+ }
140
+ }
141
+
142
+ }
93
143
94
144
}
95
145
0 commit comments