I'm trying to execute an action every time a textField
's value is changed.
@Published var value: String = ""
var body: some View {
$value.sink { (val) in
print(val)
}
return TextField($value)
}
But I get below error.
Cannot convert value of type 'Published' to expected argument type 'Binding'
If you want to observe
value
then it should be aState
This should be a non-fragile way of doing it:
I don't use combine for this. This it's working for me:
I have to say it's not my idea, I read it in this blog: SwiftUI binding: A very simple trick
In your code,
$value
is a publisher, whileTextField
requires a binding. While you can change from@Published
to@State
or even@Binding
, that can't observe the event when the value is changed.It seems like there is no way to observe a binding.
An alternative is to use
ObservableObject
to wrap your value type, then observe the publisher ($value
).Then in your view, you have have the binding
$viewModel.value
.