ios - ViewDidLoad 被调用两次 iOS 13+
问题描述
我正在为 iOS 12+ 开发一个应用程序,而 iOS 13 需要 SceneDelegate 这一事实在以编程方式显示第一个 ViewController 时给我带来了一些问题,因为我不使用情节提要。
在 AppDelegate.swift 中,我使用此代码为尚未安装 iOS 13 的设备显示 ViewController:
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
Database.database().isPersistenceEnabled = true
IQKeyboardManager.shared.enable = true
window = UIWindow()
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
window?.backgroundColor = .main
window?.rootViewController = UINavigationController(rootViewController: ViewController())
return true
}
这适用于这些设备;在 SceneDelegate.swift 中,我必须输入以下代码来呈现第一个 ViewController:
var window: UIWindow?
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 winScene = (scene as? UIWindowScene) else { return }
window = UIWindow(windowScene: winScene)
window?.backgroundColor = .main
window?.makeKeyAndVisible()
window?.rootViewController = UINavigationController(rootViewController: ViewController())
}
这完全符合我对 <13.0 iOS 版本的预期,因为我将整个 SceneDelegate.swift 标记为仅在 iOS 13 中可用,但是当我尝试在 13+ iOS 版本上运行此代码时,我的 ViewController 的 ViewDidLoad 函数得到调用了两次,因为我在技术上实例化了两次。我尝试注释掉 AppDelegate.swift 中的代码,但这不允许我的应用程序在 <13.0 iOS 版本中使用,然后我尝试注释掉 SceneDelegate.swift 中的代码,但这不允许我的适用于 13+ iOS 版本的应用程序。
有没有办法让某些代码只在 13.0 以下的版本中运行?这个问题与 Nibs、xibs 或其他问题中提到的关于 ViewDidLoad 运行两次的任何其他问题无关,请不要将其标记为与那些重复的问题,因为它不是。
谢谢你, NicopDev
解决方案
didFinishLaunchingWithOptions
使用ios 13 不要在内部执行任何操作
if #available(iOS 13.0, *) { }
else {
window = UIWindow()
window?.rootViewController = ViewController()
window?.makeKeyAndVisible()
window?.backgroundColor = .main
window?.rootViewController = UINavigationController(rootViewController: ViewController())
}
你也需要评论
window?.rootViewController = ViewController()
或者
window?.rootViewController = UINavigationController(rootViewController: ViewController())
推荐阅读
- python - 如何使用 utf-8 编码制作 lxml 输出文件
- nix - 配置 ~/.config/nixpkgs/config.nix 的位置
- php - curl 不在实时服务器中工作,但在 localhost 中运行
- python - 如何在 Python 中将 x 轴范围从 1 到 20,每个差异有 5 个?
- angular - 分配外部指令属性的角度语法?
- ionic-framework - Ionic SQLite 插件在删除时总是抛出异常
- php - 如何显示总数 年龄组
- wordpress - Wordpress 多站点的单独域名
- java - 带有多个答案的 Arraylist android studio 测验应用程序
- haskell - 如何最轻松地将具有大量导入(许多合格)的大型 Haskell 文件分解为较小的文件?