首页 > 解决方案 > 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

标签: iosswiftviewcontrollerios13viewdidload

解决方案


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

推荐阅读