我正在尝试使用 @EnvironmentObject 更新 ViewModel 中的布尔值。因此,当我导航回原始屏幕时,我希望布尔值发生变化,从而改变文本。也用 ObservedObject 试过这个。这不起作用或找不到 ContentView 在更改时重绘自身的方法。
import SwiftUI
class Global: ObservableObject {
@Published var change = [false, false]
}
struct ContentView: View {
var body: some View {
NavigationView {
VStack {
NewView().environmentObject(Global())
}
}
}
}
struct NewView: View {
@EnvironmentObject var env: Global
var body: some View {
Text(env.change[1] ? "WORKS" : "DOESNT WORK")
NavigationLink(destination: ChangeThis().environmentObject(Global())) {
Text("Push Me to Change")
}
}
}
struct ChangeThis: View {
@EnvironmentObject var env: Global
var body: some View {
Button(action: {
env.change[0] = true
env.change[1] = true
}) {
Text(" Want this to Changes the Boolean values in Global and update NewView with those values after clicking back")
}
}
}