NEW: Subscribe to Hacking with Swift+ and accelerate your learning! >>

How can you make use of a @Binding var state change in an object?

Forums > SwiftUI

I have a view with some controls for choosing a date property. I would like to use that date property in a sibling view's model to search in CoreData for a Schedule object for that date, or to create one in case there is none (the 2nd part is why I do not use a @FetchRequest). I have made the date a @Binding var so I can get the view update in the Child2 view, but I haven't found a way to pass the state changes to its model for it to do a searchOrCreate. Am I not approaching this correctly, and should I just use an Environment variable or something else?

struct ParentView: View {
  @State var day: Date = Date().noon
  var body: some View {
    VStack() {
      Child1View(day: $day)
      Child2View(day: day)
    }
  }
}

struct Child1View: View {
  @Binding var day: Date

  // code to select day
}

struct Child2View: View {
  var day: Date // I do not need to update the day in this view, 
  //just display it and use it in an object, so I did not use @Binding
  @ObservedObject private var viewModel = Child2ViewModel()

  ...
}

class Child2ViewModel: ObservableObject {
  var day: Date {
    didSet {
      // call searchOrCreate in CoreData for the Schedule object
    }

  @Published var schedule: Schedule
}

Kind regards, Sebastian

   

What I discovered works is if I create the viewModel in the parent view and pass it down:

struct ParentView: View {
  @StateObject var viewModel = Child2ViewModel()
  var body: some View {
    VStack() {
      Child1View(day: $viewModel.day)
      Child2View(viewModel: viewModel)
    }
  }
}

struct Child2View: View {
  @ObservedObject private var viewModel: Child2ViewModel
  ...
}

class Child2ViewModel: ObservableObject {
  @Published var day = Date().noon {
    didSet {
      // call searchOrCreate in CoreData for the Schedule object
    }

  @Published var schedule: Schedule
}

However, I feel like this breaks encapsulation. Ideally I would want Child2View to just get a date and proceed from there.

   

Hacking with Swift is sponsored by NSSpain

SPONSORED Announcing NSSpain 2020: Remote Edition! An online, continuous conference for iOS developers. We’ll start on Thursday and finish on Friday, with talks, activities, and lots of fun for 36 hours, non-stop. Sound good? Join us!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

Not logged in

Log in
 

Link copied to your pasteboard.