给出以下设置:
环境变量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/