SwiftUI @EnvironmentObejct似乎无法更新值

时间:2020-09-11 22:17:58

标签: swiftui swiftui-navigationlink swiftui-environment

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

enter image description here

1 个答案:

答案 0 :(得分:0)

您需要在所有视图中使用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) 
    ...
}