SHARE
TWEET

Untitled

a guest Aug 20th, 2019 72 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. final class ViewModel: ObservableObject {
  2.     @Published var state = State()
  3.  
  4.     func updateBoolean(code: String, value: Bool) {
  5.         state.items = state.items.map {
  6.             if $0.code == code {
  7.                 var newItem = $0
  8.                 newItem.isOn = value
  9.                 return newItem
  10.             }
  11.  
  12.             return $0
  13.         }
  14.     }
  15. }
  16.  
  17. struct State {
  18.     var items: [Item] = []
  19. }
  20.  
  21. struct Item {
  22.     var isOn: Bool = false
  23. }
  24.  
  25. struct MyView: View {
  26.     @ObservedObject var viewModel: ViewModel
  27.  
  28.     var body: some View {
  29.         Form {
  30.             ForEach(viewModel.state.items, id: \.self) { item in
  31.                         BooleanSection(
  32.                             label: item.name) { isOn in
  33.  
  34.                             self.viewModel.updateBoolean(
  35.                                 code: item.code,
  36.                                 value: isOn
  37.                             )
  38.                             print("Changed section boolean with -> \(isOn)")
  39.                         }
  40.             }
  41.         }
  42.     }
  43. }    
  44.  
  45. struct BooleanSection: View {
  46.         @State var isOn = false
  47.         let label: String
  48.         let onChange: (Bool) -> Void
  49.  
  50.         var binding: Binding<Bool> {
  51.             return Binding(get: {
  52.                 return self.isOn
  53.             }, set: { isOn in
  54.                 self.isOn = isOn
  55.                 self.onChange(isOn)
  56.             })
  57.         }
  58.  
  59.         var body: some View {
  60.             Section {
  61.                 Toggle(label, isOn: binding)
  62.             }
  63.         }
  64.     }
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
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top