如何解决如何在 AppDelegate.swift
我尝试创建一个 Rootviewmodel 实例,方法是在应用启动时将其注入 RootViewController,在 didFinishLaunchingWithOptions 的 >AppDelegate.swift 所以它不会被多次创建。
这是代码片段:
...
var window: UIWindow?
func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
guard let rootViewController = window?.rootViewController as? RootViewController else {
fatalError("Unable to Instantiate the root view controller")
}
let rootviewmodel = Rootviewmodel()
rootViewController.viewmodel = rootviewmodel
return true
}
...
Rootviewmodel 是一个尚未实现的基本 swift 类,RootViewController 有一个可选的 viewmodel 属性以允许注入。
这是我的问题:每次我运行应用程序时,它都会在我创建的 fatalError 处停止,以了解在创建 rootViewController 时是否一切顺利。所以,这意味着一切都不顺利。
我认为在创建 rootViewController 时 window 属性仍然为 null,但我不知道如何解决这个问题。
我尝试在 SceneDelegate 中创建相同的内容,但没有成功。
我该怎么做才能解决这个问题?我使用的是 XCode 12.5 版
解决方法
由于您采用了新的场景生命周期并拥有场景委托,您需要在 willConnectTo
场景委托函数中访问根视图控制器。
这是因为您的应用可能不再有单个窗口,但如果您(例如)在 iPadOS 上支持多个视图,则可能有多个窗口。
func scene(_ scene: UIScene,willConnectTo session: UISceneSession,options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard,the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
guard let scene = (scene as? UIWindowScene) else { return }
if let rootVC = scene.windows.first?.rootViewController as? RootViewController {
rootViewController.viewModel = RootViewModel()
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。