如何从类(扩展名)写入SwiftUI环境对象

时间:2020-01-01 15:08:43

标签: ios swift swiftui

进行以下设置:

环境变量UserState

class UserState: ObservableObject {
    @Published var loggedIn = Auth.auth().currentUser != nil
}

UserState作为SceneDelegate

中的变量
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
   ...

   //creating the variable
   var userState = UserState()

   func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
       window.rootViewController = UIHostingController(rootView: ContentView().environmentObject(userState))
   }

   ...
}

我现在可以通过声明完美地在SwiftUI视图中读取/写入此变量

struct ProfileTab: View {
    @EnvironmentObject var userState: UserState
    var body: some View {
        // here I could easily read/write to userState
    }
}

到目前为止一切顺利。但: 在SwiftUI视图之外写入此变量的正确方法是什么?例如。来自课程或课程扩展。

示例

extension AppDelegate {

    func something(loggedIn: Bool) {
        // here I would like to access the environment variable. Something like
        // userState.loggedIn = loggedIn
    }

}

1 个答案:

答案 0 :(得分:6)

这是可行的方法...

class AppDelegate: UIResponder, UIApplicationDelegate {
   //creating the variable in AppDelegate to have it shared
   var userState = UserState()
   ...

那么,那么您可以...

extension AppDelegate {

    func something(loggedIn: Bool) {
        // just use it here as now it is own property
        self.userState.loggedIn = loggedIn
    }
}

并通过共享应用程序实例在场景委托中使用它

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
   ...

 func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
   // safe as it is known the one AppDelegate
   let appDelegate = UIApplication.shared.delegate as! AppDelegate
   window.rootViewController = UIHostingController(rootView: 
       ContentView().environmentObject(appDelegate.userState))
 }