无法在 AppDelegate 中以编程方式将 viewContoller 添加到 Tab Bar

问题描述

我正在尝试通过 didFinishLaunchWithOptions 以编程方式将 viewController 添加到现有的 Tab Bar,但我的代码不起作用,我无法将 rootViewController 向下转换为 UITabBarController。

func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        if let tabBarController = window?.rootViewController as? UITabBarController {
            print("rootVC")
            let storyboard = UIStoryboard(name: "Main",bundle: nil)
            let vc = storyboard.instantiateViewController(withIdentifier: "NavController")
            vc.tabBarItem = UITabBarItem(tabBarSystemItem: .topRated,tag: 1)
            tabBarController.viewControllers?.append(vc)
        }

        return true
    }

这是我的故事板,我觉得这里没问题,Tab Bar Contoller 是初始视图控制器...

主故事板

Main.storyboard

解决方法

在 iOS 13+ 中,应用委托中的 didFinishLaunchingWithOptions 窗口将为零。而是将您的代码移动到 willConnectTo session 中的 SceneDelegate 方法:

func scene(_ scene: UIScene,willConnectTo session: UISceneSession,options connectionOptions: UIScene.ConnectionOptions) {
    if let tabBarController = window?.rootViewController as? UITabBarController {
        print("rootVC")
        let storyboard = UIStoryboard(name: "Main",bundle: nil)
        let vc = storyboard.instantiateViewController(withIdentifier: "NavController")
        vc.tabBarItem = UITabBarItem(tabBarSystemItem: .topRated,tag: 1)
        tabBarController.viewControllers?.append(vc)
    }
    guard let _ = (scene as? UIWindowScene) else { return }
}