【发布时间】:2019-11-21 14:09:55
【问题描述】:
在我的 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 anzeigen") }
}
Spacer()
}.colorScheme(.dark)
}
}
所需的行为是当 Toggle() 更改其状态时触发操作“PWSStore.shared.toggleIsDisplayed(station)”。
【问题讨论】:
-
因为我不知道你的应用程序幕后发生的一切,这可能不是一个解决方案,但由于
station是BindableObject,你不能只替换@987654324 @ 和Toggle(isOn: $station.isDisplayed)然后更新didSet中的PWSStore.sharedisDisplayedPWS类? -
@graycampbell 理论上可行(这是我之前尝试过的)。不幸的是,我的 PWS 类(它是一个核心日期实体)的 didChangeValue(forKey:) 函数经常被调用。在某些情况下(例如按下切换按钮),“isDisplayed”的值确实发生了变化(--> 应该触发该操作)。在其他情况下,'isDisplayed' 的值会用旧值“更新”(--> 操作不必被触发)。我还没有找到区分这两种情况的方法。因此,我尝试直接在视图中触发操作。