Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

ios - Can't add viewContoller to Tab Bar programmatically in the AppDelegate

I'm trying to add a viewController to the existing Tab Bar programmatically through didFinishLaunchWithOptions, but my code doesn't work, i can't downcast the rootViewController as 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
    }

Here is my storyboard, i think here is all okay, Tab Bar Contoller is initial view Controller...

Main.storyboard Main.storyboard

question from:https://stackoverflow.com/questions/65932261/cant-add-viewcontoller-to-tab-bar-programmatically-in-the-appdelegate

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In iOS 13+ the window will be nil from didFinishLaunchingWithOptions in the app delegate. Instead move your code to willConnectTo session method in 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 }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...