如何解决onReceive方法调用的Swift编译器错误?

问题描述 投票:0回答:2

我使用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部分,否则不会编译。错误消息是“无法推断闭包类型”,但是注释该方法似乎仅给我其他错误,而不是编译错误。

如何纠正此代码段?

swift swiftui
2个回答
0
投票

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

0
投票

由于无法删除此问题,我将在此处自行发布答案。

我遇到的问题是我试图将@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)
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.