I feel like I'm misunderstanding how Binding works in SwiftUI, in that I do not understand why the first TextField below does not update when the text view model property changes:
class MyViewModel: ObservableObject {
@Published var text: String = "Hello"
var binding: Binding<String>!
init() {
binding = Binding(get: { self.text }, set: { self.text = $0 })
}
}
struct MyView: View {
@StateObject var viewModel = MyViewModel()
var body: some View {
VStack {
Text("Actual: " + viewModel.text)
TextField("Field 1", text: viewModel.binding)
TextField("Field 2", text: $viewModel.text)
}
}
}
struct MyView_Previews: PreviewProvider {
static var previews: some View {
MyView()
}
}
Typing in the first TextField always updates second one (and the Text label), but typing in the second TextField only propagates changes to the Text label, shown here:
In my actual use case, the list of TextField views is dynamically generated from a user-defined template, likewise with custom bindings to a @Published complex object (i.e. not as simple as a String) on MyViewModel. In my limited experience, I believe the dynamic nature of the view prevents me from coding it in a straight-forward fashion, as seen with the second TextField.
My guess is that SwiftUI has no insight that the custom binding should even need to be refreshed, in which case my question becomes: How can I tell the binding to "refresh" the TextField while also supporting dynamically-generated content?
