How to observe a TextField value with SwiftUI and Combine?

Sorin Lica picture Sorin Lica · Jun 24, 2019 · Viewed 7.3k times · Source

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'

Answer

valexa picture valexa · Sep 26, 2019

This should be a non-fragile way of doing it:

class MyData: ObservableObject {
    var value: String = "" {
        willSet(newValue) {
            print(newValue)
        }
    }
}

struct ContentView: View {
    @ObservedObject var data = MyData()
    var body: some View {
        TextField("Input:", text: $data.value)
    }
}