How do I connect @Published in model to @Binding in a View?

Generated on 8/6/2024

1 search

To connect @Published in a model to @Binding in a SwiftUI view, you can follow these steps:

  1. Define the Model with @Published Property: Create a model class that conforms to ObservableObject and use the @Published property wrapper for the property you want to observe.

    class Pet: ObservableObject {
        @Published var rating: Int = 0
    }
    
  2. Create a View with @Binding: Define a SwiftUI view that takes a @Binding to the property you want to bind.

    struct RatingView: View {
        @Binding var rating: Int
    
        var body: some View {
            VStack {
                Text("Rating: \(rating)")
                Button("Increase Rating") {
                    rating += 1
                }
            }
        }
    }
    
  3. Bind the Model Property to the View: In your main view, create an instance of the model and pass a binding to the view.

    struct ContentView: View {
        @StateObject private var pet = Pet()
    
        var body: some View {
            RatingView(rating: $pet.rating)
        }
    }
    

This setup ensures that changes in the model's @Published property are reflected in the view, and vice versa.

For more detailed information, you can refer to the SwiftUI essentials session from WWDC 2024, which discusses how to use @Binding to create a two-way reference to the state of another view.