1

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

在此处输入图像描述

4

1 回答 1

1

您需要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) 
    ...
}
于 2020-09-11T22:28:47.660 回答