4

Following this cheat sheet I'm trying to figure out data flow in SwiftUI. So:

Use @Binding when your view needs to mutate a property owned by an ancestor view, or owned by an observable object that an ancestor has a reference to.

And that is exactly what I need so my embedded model is:

class SimpleModel: Identifiable, ObservableObject {
    @Published var values: [String] = []

    init(values: [String] = []) {
        self.values = values
    }
}

and my View has two fields:

struct SimpleModelView: View {
    @Binding var model: SimpleModel
    @Binding var strings: [String]

    var body: some View {
        VStack {
            HStack {
                Text(self.strings[0])
                TextField("name", text: self.$strings[0])
            }
            HStack {
                Text(self.model.values[0])
                EmbeddedView(strings: self.$model.values)
            }
        }
    }
}

struct EmbeddedView: View {
    @Binding var strings: [String]

    var body: some View {
        VStack {
            TextField("name", text: self.$strings[0])
        }
    }
}

So I expect the view to change Text when change in input field will occur. And it's working for [String] but does not work for embedded @Binding object:

enter image description here

Why it's behaving differently?

2 Answers 2

2

Make property published

class SimpleModel: Identifiable, ObservableObject {
    @Published var values: [String] = []

and model observed

struct SimpleModelView: View {
    @ObservedObject var model: SimpleModel

Note: this in that direction - if you introduced ObservableObject then corresponding view should have ObservedObject wrapper to observe changes of that observable object's published properties.

Sign up to request clarification or add additional context in comments.

2 Comments

Did that - same issue unfortunately
Great! Thanks now it's working and understand principle here, but still not sure why @Binding with @Published as you suggested in a first time it's not working 🤔 From my understanding the docs and description it should change Text same way since it's "bind"
1

In SimpleModelView, try changing:

@Binding var model: SimpleModel

to:

@ObservedObject var model: SimpleModel

@ObservedObjects provide binding values as well, and are required if you want state changes from classes conforming to ObservableObject

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.