Skip to content

Commit 90d0726

Browse files
authored
Update LocalState - onChange (#30)
1 parent 8ef5319 commit 90d0726

File tree

1 file changed

+54
-4
lines changed

1 file changed

+54
-4
lines changed

Sources/SwiftUISupport/Components/LocalState.swift

Lines changed: 54 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,52 @@
1-
21
import SwiftUI
3-
4-
/**
2+
/*
53
A stateful view in a closure or function-based component instead of a struct-based view.
64
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+
```
726
*/
8-
public struct LocalState<State, Content: View>: View {
27+
public struct LocalState<State: Equatable, Content: View>: View {
928

1029
@SwiftUI.State var state: State
1130

1231
private let content: (Binding<State>) -> Content
1332

33+
private let onChange: (State) -> Void
34+
1435
public init(
1536
initial: State,
37+
onChange: @escaping (State) -> Void = { _ in },
1638
@ViewBuilder content: @escaping (Binding<State>) -> Content
1739
) {
40+
self.onChange = onChange
1841
self._state = .init(initialValue: initial)
1942
self.content = content
2043
}
2144

2245
public var body: some View {
2346
content($state)
47+
.onChange(of: state) { newValue in
48+
onChange(newValue)
49+
}
2450
}
2551

2652
}
@@ -34,6 +60,8 @@ struct BookState: View, PreviewProvider {
3460

3561
static var previews: some View {
3662
Self()
63+
Content3()
64+
.previewDisplayName("Binding")
3765
}
3866

3967
private struct Content: View {
@@ -90,6 +118,28 @@ struct BookState: View, PreviewProvider {
90118
}
91119
}
92120

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+
}
93143

94144
}
95145

0 commit comments

Comments
 (0)