SHARE
TWEET

Untitled

a guest Aug 21st, 2019 66 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. struct StateUpdatedPreferenceKey: PreferenceKey {
  2.     static var defaultValue: Int = Int.min
  3.     static func reduce(value: inout Int, nextValue: () -> Int) {
  4.         value = nextValue()
  5.     }
  6. }
  7.  
  8. struct StateUpdated: View {
  9.     var value: Int
  10.     var onChange: () -> Void
  11.  
  12.     var body: some View {
  13.         Color.clear
  14.             .preference(key: StateUpdatedPreferenceKey.self, value: self.value)
  15.             .onPreferenceChange(StateUpdatedPreferenceKey.self) { _ in
  16.                 self.onChange()
  17.         }
  18.     }
  19. }
  20.  
  21. struct ViewPlayground: View {
  22.     @State var isEven: Bool = true
  23.     @State var count: Int = 0
  24.  
  25.     var body: some View {
  26.         VStack {
  27.             Button("Update") {
  28.                 self.count += 1
  29.             }
  30.             Text("\(self.count)")
  31.             Text("Is Even: \(self.isEven.description)")
  32.                 .background(StateUpdated(value: self.count, onChange: {
  33.                     DispatchQueue.main.async {
  34.                         self.isEven = self.count%2 == 0
  35.                     }
  36.                 }))
  37.             Text("Is really even: \(self.reallyIsEven().description)")
  38.             Text("Matches " + self.reallyIsEven().description)
  39.         }
  40.         .execute { // extension on View to execute a block
  41.             print("Matches " + self.matches().description)
  42.         }
  43.     }
  44.  
  45.     func reallyIsEven() -> Bool {
  46.         self.count%2 == 0
  47.     }
  48.  
  49.     func matches() -> Bool {
  50.         self.isEven == self.reallyIsEven()
  51.     }
  52. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top