Skip to content

Instantly share code, notes, and snippets.

@timothycosta
Created August 9, 2019 08:33
Show Gist options
  • Save timothycosta/b17477f5a26f1ae8aff03f4436216aa5 to your computer and use it in GitHub Desktop.
Save timothycosta/b17477f5a26f1ae8aff03f4436216aa5 to your computer and use it in GitHub Desktop.
Resetting @State when other state changes
struct StateUpdatedPreferenceKey: PreferenceKey {
static var defaultValue: Int = Int.min
static func reduce(value: inout Int, nextValue: () -> Int) {
value = nextValue()
}
}
struct StateUpdated: View {
var value: Int
var onChange: () -> Void
var body: some View {
Color.clear
.preference(key: StateUpdatedPreferenceKey.self, value: self.value)
.onPreferenceChange(StateUpdatedPreferenceKey.self) { _ in
self.onChange()
}
}
}
struct ViewPlayground: View {
@State var isEven: Bool = true
@State var count: Int = 0
var body: some View {
VStack {
Button("Update") {
self.count += 1
}
Text("\(self.count)")
Text("Is Even: \(self.isEven.description)")
.background(StateUpdated(value: self.count, onChange: {
DispatchQueue.main.async {
self.isEven = self.count%2 == 0
}
}))
Text("Is really even: \(self.reallyIsEven().description)")
Text("Matches " + self.reallyIsEven().description)
}
.execute { // extension on View to execute a block
print("Matches " + self.matches().description)
}
}
func reallyIsEven() -> Bool {
self.count%2 == 0
}
func matches() -> Bool {
self.isEven == self.reallyIsEven()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment