//在ContentView.swift中:
struct ContentView: View {
@EnvironmentObject var app_state_instance : AppState //this is set to a default of false.
var body: some View {
if self.app_state_instance.complete == true {
Image("AppIcon")
}}
public class AppState : ObservableObject {
@Published var inProgress: Bool = false
@Published var complete : Bool = false
public static var app_state_instance: AppState? //I init this instance in SceneDelegate & reference it throughout the app via AppState.app_state_instance
...
}
在AnotherFile.swift中:
AppState.app_state_instance?.complete = true
在SceneDelegate.swift中:
app_state_instance = AppState( UserDefaults.standard.string(forKey: "username"), UserDefaults.standard.string(forKey: "password") )
AppState.app_state_instance = app_state_instance
window.rootViewController = UIHostingController(rootView: contentView.environmentObject(app_state_instance!))
此^不会触发我的视图更新。有人知道为什么吗?
还可以发布一个静态var @吗?
此外,我对基于类+值作为结构的范式有点陌生,如果您有任何改进建议,请分享。
我已经考虑使用“ inout” ContentView结构引用从其他文件更新结构状态(因为通过app_state_instance不能使用此代码)。