如何在Swift项目中从一个选项卡栏项切换到另一个

问题描述

我有一个标签栏控制器实例,其中有5个导航控制器作为其标签栏项。我希望能够通过选项卡栏以编程方式从一个视图控制器切换到另一个导航控制器,但我一直在努力了解如何做到这一点,甚至是可能的话。

这是我到目前为止尝试过的:

        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,let sceneDelegate = windowScene.delegate as? SceneDelegate
        else {
          return
        }
        let tabBarController = sceneDelegate.window?.rootViewController as? UITabBarController
        guard let controller = tabBarController?.viewControllers?[2] as? UINavigationController else { return }
        controller.popToRootViewController(animated: true)
        dismiss(animated: true,completion: nil)

解决方法

我需要做的只是tabBarController.selectedIndex = 2