SwiftUI @EnvironmentObejct 似乎无法更新值

SwiftUI @EnvironmentObejct can't seem update values

我正在尝试使用@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")
        }
    }
}

您需要在所有视图中使用相同的 Global EnvironmentObject 实例:

struct NewView: View {
    @EnvironmentObject var env: Global
    ...
    // pass the already-existing instance, don't create a new one
    NavigationLink(destination: ChangeThis().environmentObject(env) 
    ...
}