如何使用SwiftUI和Combine观察TextField值? [英] How to observe a TextField value with SwiftUI and Combine?
本文介绍了如何使用SwiftUI和Combine观察TextField值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
每次尝试更改 textField
的值时,我都试图执行一个动作.
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)
}
但是我遇到了错误.
无法将类型为已发布"的值转换为预期的参数类型绑定"
Cannot convert value of type 'Published' to expected argument type 'Binding'
推荐答案
这应该是一种非脆弱的方法:
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)
}
}
这篇关于如何使用SwiftUI和Combine观察TextField值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文