How to observe a TextField value with SwiftUI and Combine?

坚强是说给别人听的谎言 提交于 2019-12-24 12:28:23

问题


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'


回答1:


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)
    }
}



回答2:


If you want to observe value then it should be a State

@State var value: String = ""


来源:https://stackoverflow.com/questions/56735382/how-to-observe-a-textfield-value-with-swiftui-and-combine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!