UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

2      

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.

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.