首页 > 解决方案 > 使用 TabBarViewController 呈现 NavigationController 无法以编程方式选择索引

问题描述

我正在尝试呈现 NavigationController 并在完成块中选择第二个选项卡。我的代码是:

let chatViewController = UITabBarController()
let navigationController = UINavigationController(rootViewController: chatViewController)

present(navigationController, animated: true, completion: {
    self.visibleViewController = navigationController
    self.visibleViewController?.tabBarController?.selectedIndex = 1
})

第二次尝试:

let chatViewController = UITabBarController()
let navigationController = UINavigationController(rootViewController: chatViewController)
navigationController.tabBarController?.selectedIndex = 1

present(navigationController, animated: true, completion: {
    self.visibleViewController = navigationController
})

在这两种情况下,tabBarController 都是 nil。如何切换到不同的选项卡?

标签: iosswiftiphoneuinavigationcontrollerswift5

解决方案


您正在尝试访问UITabBarControllerUINavigationController但您需要从那里访问第一个控制器,UINavigationController您需要UITabBar像这样选择:

func showTabBarControllerr() {
    let chatViewController = UITabBarController()
    //Note: Make sure you have already added the Controllers in Tabbarcontroller
    chatViewController.viewControllers = [DemoOne(), DemoTwo()]
    let navigationController = UINavigationController(rootViewController: chatViewController)
    present(navigationController, animated: true, completion: {
        if let tabBarController = navigationController.viewControllers.first as? UITabBarController {
            tabBarController.selectedIndex = 1
        }
    })
}

让我知道这有没有帮助!


推荐阅读