每次渲染主体时调用SwiftUI Picker onReceive()

每次渲染主体时调用SwiftUI Picker onReceive(),swiftui,Swiftui,我正在使用选择器显示分段控件,并希望知道选择器值何时更改,以便执行非UI操作。使用建议的onReceive()修饰符(如建议的那样)不起作用,因为每次渲染主体时都会调用它 以下是我的代码: struct PickerView: View { @State private var weather = 0 @State private var showMessage = false var body: some View { VStack(spacing

我正在使用
选择器
显示分段控件,并希望知道选择器值何时更改,以便执行非UI操作。使用建议的
onReceive()
修饰符(如建议的那样)不起作用,因为每次渲染主体时都会调用它

以下是我的代码:

struct PickerView: View {

    @State private var weather = 0
    @State private var showMessage = false

    var body: some View {

        VStack(spacing: 24) {
            Picker(selection: $weather, label: Text("Weather")) {
                Image(systemName: "sun.max.fill").tag(0)
                Image(systemName: "cloud.sun.rain.fill").tag(1)
            }
            .pickerStyle(SegmentedPickerStyle())
            .frame(width: 120, height: 48)
            .onReceive([weather].publisher.first()) { connectionType in
                print("connection type is: \(connectionType)")
            }

            Button(action: { self.showMessage.toggle() }) {
                Text("Press Me")
            }

            if showMessage {
                Text("Hello World")
            }
        }
    }
}
无论何时渲染主体,都会调用
onReceive()
块,包括第一次和任何时候按下按钮(显示消息的切换)


知道为什么会发生这种情况,以及我只能在选择器值更改时如何反应吗?

这里是可能的解决方案,而不是
。onReceive

Picker(selection: Binding(           // << proxy binding
                get: { self.weather },
                set: { self.weather = $0
                    print("connection type is: \($0)")  // side-effect
                })
    , label: Text("Weather")) {
    Image(systemName: "sun.max.fill").tag(0)
    Image(systemName: "cloud.sun.rain.fill").tag(1)
}

Picker(选择:Binding(//代理绑定,回答Asperi posted;)