首页 > 解决方案 > 如何在 xcode 11 中为新项目使用特定的根控制器初始化 uiwindow?

问题描述

我想在里面初始化窗口appDelegate以显示具体ViewController取决于某些情况。现在我有这个代码:

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        window = UIWindow()

        let rootNavigationController = UIViewController()
        window?.rootViewController = rootNavigationController
        window?.rootViewController?.view.backgroundColor = .green

        window?.makeKeyAndVisible()
        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }

}

我正在使用XCode11并创建了新项目。SceneDelegate 我删除的文件,因为它对此没有影响。Info.plist还从部署信息中删除了 Main

结果在设备上我看到黑屏,但调试器显示 rootNavigationController 应该是 来自调试器的图像

如何修复它或实现这个逻辑XCode11

标签: iosswiftxcodeappdelegate

解决方案


解决方案: 1)在 manifest(plist) 文件中删除 Storyboard Name 字段 2)在 SceneDelegate.swift 中实现:

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 }
        window = UIWindow(windowScene: windowScene)

        let rootNavigationController = UIViewController()
        window?.rootViewController = rootNavigationController
        window?.rootViewController?.view.backgroundColor = .green
        window?.makeKeyAndVisible()
    }

它适用于 ios 13 ,如果你想支持 ios 12 及更低版本,你还需要在 AppDelegate 中实现这个逻辑


推荐阅读