【问题标题】:Can't add viewContoller to Tab Bar programmatically in the AppDelegate无法在 AppDelegate 中以编程方式将 viewContoller 添加到选项卡栏
【发布时间】:2025-12-30 09:55:06
【问题描述】:

我正在尝试通过didFinishLaunchWithOptions 以编程方式将 viewController 添加到现有标签栏,但我的代码不起作用,我无法将 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 swift xcode downcast


    【解决方案1】:

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

    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 }
    }
    

    【讨论】: