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

标签 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 View 中完美地读取/写入该变量

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

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

示例

extension AppDelegate {

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

}

最佳答案

这是可能的方法...

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
    }
}

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

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))
 }

关于ios - 如何从类(-扩展名)写入 SwiftUI 环境对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59553592/

相关文章:

ios - iphone:.dSYM 文件位于崩溃报告中的位置

ios - 在我的 cocoapod 中包含一个 plist 文件

swift - 监视和控制具有延迟反馈的设备的正确方法是什么?

ios - SwiftUI - 创建多平台应用程序时,如何更改场景中的 View ?

swift - Xcode:方法参数的代码完成

ios - SwiftUI - 显示和隐藏自定义警报

ios - 从tableView中删除多个单元格不冲突

iOS - UITableViewCell 图像调整/调整大小

swift - 在屏幕上移动 SKSpriteNode

ios - iOS应用程序在Xcode控制台以外的地方记录日志