gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:19:19 26 4
gpt4 key购买 nike

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

这是我的代码:

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() block 将在主体呈现时被调用,包括第一次和任何时候按钮(切换显示消息)被按下。

知道为什么会发生这种情况,以及我如何才能仅在选择器值更改时使用react?

最佳答案

这里是可能的解决方案而不是 .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)
}

关于每次渲染主体时调用 SwiftUI Picker onReceive(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62839932/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com