Created
August 9, 2019 08:33
-
-
Save timothycosta/b17477f5a26f1ae8aff03f4436216aa5 to your computer and use it in GitHub Desktop.
Resetting @State when other state changes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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