我使用Xcode 11.1在操场上隔离了这段代码:
import SwiftUI
import PlaygroundSupport
struct ContentView: View {
@State var name: String = ""
var body: some View {
List {
Text(String(describing: name))
TextField("First Name", text: $name)
}.onReceive($name) { n in
print("hey \(n)")
}
}
}
let uv = ContentView()
PlaygroundPage.current.liveView = UIHostingController(rootView: uv)
除非我省略onReceive部分,否则不会编译。错误消息是“无法推断闭包类型”,但是注释该方法似乎仅给我其他错误,而不是编译错误。
如何纠正此代码段?
onReceive
函数采用发布者类型,因此您必须将$name
更改为name.publisher
。
var body: some View {
List {
Text(String(describing: name))
TextField("First Name", text: $name)
}.onReceive(name.publisher) { n in
print("hey \(n)")
}
}
由于无法删除此问题,我将在此处自行发布答案。
我遇到的问题是我试图将@State
转换为Publisher
,并且onReceive
需要Publisher
(如@jfuellert所指出)。在后续问题(我删除的问题)中,用户@matt将我的用例指向了@ObservedObject
。
[我在这里尝试使用@State
进行操作的一种直接方法是利用这样的事实,即每次状态var更改时,主体都会重新评估:
struct ContentView: View {
@State var name: String = ""
var body: some View {
print("hey \(name)")
return List {
Text(String(describing: name))
TextField("First Name", text: $name)
}
}
}