May 12, 2024 iOS

How to tell SwiftUI views to bind to nested ObservableObjects

In SwiftUI, you can bind views to nested ObservableObjects by passing those objects down through the view hierarchy. This allows child views to access and modify the properties of the nested observable objects. Here’s a step-by-step guide:

1.Define Your ObservableObject Classes: First, define your observable object classes, including any nested observable objects.

import Combine

class InnerObject: ObservableObject {
    @Published var innerProperty: String = "Inner Value"
}

class OuterObject: ObservableObject {
    @Published var outerProperty: String = "Outer Value"
    @Published var innerObject = InnerObject()
}

2.Create Your Views: Create your views and pass down the outer observable object to any child views that need access to it.

import SwiftUI

struct ContentView: View {
    @ObservedObject var outerObject = OuterObject()

    var body: some View {
        VStack {
            Text("Outer Property: \(outerObject.outerProperty)")
            ChildView(innerObject: outerObject.innerObject)
        }
    }
}

struct ChildView: View {
    @ObservedObject var innerObject: InnerObject

    var body: some View {
        Text("Inner Property: \(innerObject.innerProperty)")
    }
}

In this example:

  • ContentView creates an instance of OuterObject and passes it down to ChildView.
  • ChildView takes an instance of InnerObject as a parameter.

3.Update Nested Properties: Now, you can update properties of the nested observable objects directly from your views, and SwiftUI will automatically reflect those changes.

struct ContentView: View {
    @ObservedObject var outerObject = OuterObject()

    var body: some View {
        VStack {
            Text("Outer Property: \(outerObject.outerProperty)")
            ChildView(innerObject: outerObject.innerObject)
            Button("Change Inner Property") {
                outerObject.innerObject.innerProperty = "New Inner Value"
            }
        }
    }
}

When the “Change Inner Property” button is tapped, it updates the innerProperty of the nested InnerObject. Since ChildView is observing changes to innerObject, it will automatically re-render with the updated value.