使在 Xcode 11 中创建的项目向后兼容

Making project created in Xcode 11 backwards compatible

我使用 Xcode 11 创建了一个新项目。我习惯于以编程方式创建 UIWindow 的根视图控制器,我首先注意到这个新的 SceneDelegate 文件。经过一些研究,我发现了一篇描述如何使用这个新的 UIScene API 创建根视图控制器的文章,它似乎工作正常。但是,我找不到对较低的 iOS 版本执行相同操作的方法,因为 AppDelegate class 现在不再有 window 属性。所以我的问题是如何以编程方式为其他 iOS 版本创建根视图控制器?

如果有人遇到同样的事情,这里是代码。

iOS 13 个工作流程

代码取自 this 文章。

在您的 SceneDelegate 文件中:

    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 windowScene = (scene as? UIWindowScene) else { return }
        self.window = UIWindow(frame: windowScene.coordinateSpace.bounds)
        self.window?.windowScene = windowScene

        let controller = UIViewController()
        let navigationController = UINavigationController(rootViewController: controller)

        self.window?.rootViewController = navigationController
        self.window?.makeKeyAndVisible()
    }


iOS 12 岁及以下

在您的 AppDelegate 文件中:

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        if #available(iOS 13.0, *) { return true }

        self.window = UIWindow(frame: UIScreen.main.bounds)

        let controller = UIViewController()
        let navigationController = UINavigationController(rootViewController: controller)

        self.window?.rootViewController = navigationController
        self.window?.makeKeyAndVisible()

        return true
    }                         


UIWindow 保存在变量中以使其显示很重要。