在我的 SwiftUI 视图中,当 Toggle() 更改其状态时,我必须触发一个操作。切换本身只需要一个绑定。因此,我尝试在 @State 变量的 didSet 中触发操作。但是 didSet 永远不会被调用。
是否有任何(其他)方式来触发一个动作?或者有什么方法可以观察@State 变量的值变化?
我的代码如下所示:
struct PWSDetailView : View {
@ObjectBinding var station: PWS
@State var isDisplayed: Bool = false {
didSet {
if isDisplayed != station.isDisplayed {
PWSStore.shared.toggleIsDisplayed(station)
}
}
}
var body: some View {
VStack {
ZStack(alignment: .leading) {
Rectangle()
.frame(width: UIScreen.main.bounds.width, height: 50)
.foregroundColor(Color.lokalZeroBlue)
Text(station.displayName)
.font(.title)
.foregroundColor(Color.white)
.padding(.leading)
}
MapView(latitude: station.latitude, longitude: station.longitude, span: 0.05)
.frame(height: UIScreen.main.bounds.height / 3)
.padding(.top, -8)
Form {
Toggle(isOn: $isDisplayed)
{ Text("Wetterstation …Run Code Online (Sandbox Code Playgroud)