The best way is to wrap the property in an ObservableObject
:
final class TextStore: ObservableObject {
@Published var text: String = "" {
didSet { ... }
}
}
And then use that ObservableObject
's property as a binding variable in your view:
struct ContentView: View {
@ObservedObject var store = TextStore()
var body: some View {
TextField("", text: $store.text)
}
}
didSet
will now be called whenever text
changes.
Alternatively, you could create a sort of makeshift Binding
value:
TextField("", text: Binding<String>(
get: {
return self.text
},
set: { newValue in
self.text = newValue
...
}
))
Just note that with this second strategy, the get
function will be called every time the view is updated. I wouldn't recommend using this approach, but nevertheless it's good to be aware of it.