SWIFTUI: Pass data via ObservedObject to children-Views

I want to pass data of a class from parent View to children Views (children are in separate files) by using @ObservableObject / @ObservedObject. Do you have a typical example?  What is wrong in the following coding or what is required to get it working:

class Einstellungen: ObservableObject {

  @Published var scanDauer: Double = 10 

  … }

struct ContentView: View {

  @ObservedObject var einstellungen = Einstellungen() 

  var body: some View {

    NavigationView {

    NavigationLink(destination: BLE_View()) {  …

struct BLE_View: View {

  @ObservedObject var einstellungen: Einstellungen

  var body: some View {

After error “Missing argument for parameter 'einstellungen' in call”: If I add an argument to the call as shown, I get an error as:

        NavigationLink(destination: BLE_View(einstellungen: Einstellungen)) { // Cannot convert value of type 'Einstellungen.Type' to expected argument type 'Einstellungen'

Similar issue for children. What corrections are required for parent and children including PreviewProvider?

 

Answered by DTS Engineer in 739297022

In ContentView, you create an instance of class Einstellungen, and that's the object being observed by the view:

  @ObservedObject var einstellungen = Einstellungen() 

In BLE_View, you want to observe the same instance, so you would pass it into the View as a parameter:

NavigationLink(destination: BLE_View(einstellungen: einstellungen))

Your original code didn't compile because you were trying to pass in the class type (Einstellungen) instead of an instance of the class (einstellungen).

Accepted Answer

In ContentView, you create an instance of class Einstellungen, and that's the object being observed by the view:

  @ObservedObject var einstellungen = Einstellungen() 

In BLE_View, you want to observe the same instance, so you would pass it into the View as a parameter:

NavigationLink(destination: BLE_View(einstellungen: einstellungen))

Your original code didn't compile because you were trying to pass in the class type (Einstellungen) instead of an instance of the class (einstellungen).

Thanks a lot. Correction helped, and after modifying PreviewProvider in

 struct BLE_View_Previews: PreviewProvider {     static var previews: some View {     BLE_View (einstellungen: Einstellungen())     } }

everything is OK. Thanks again!

SWIFTUI: Pass data via ObservedObject to children-Views
 
 
Q