Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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()
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement