以编程方式切换到TabBar选项卡视图?

173
假设我在iPhone应用程序的一个选项卡视图中有一个UIButton,并且我想让它打开TabBarController标签栏中的另一个选项卡。 我该如何编写代码来实现这一点?
我假设我要卸载现有视图并加载特定的选项卡视图,但我不确定如何编写代码。

我在上面的方法中遇到了问题,大家可以在我的问题中帮忙吗? - Roman Simenok
12个回答

0

像 Stuart Clark 的解决方案一样,但适用于 Swift 3,并使用恢复标识符来查找正确的选项卡:

private func setTabById(id: String) {
  var i: Int = 0
  if let controllers = self.tabBarController?.viewControllers {
    for controller in controllers {
      if let nav = controller as? UINavigationController, nav.topViewController?.restorationIdentifier == id {
        break
      }
      i = i+1
    }
  }
  self.tabBarController?.selectedIndex = i
}

使用方法如下("Humans"和"Robots"也必须在故事板中设置为特定的视图控制器和其恢复ID,或者使用故事板ID并将"使用故事板ID"选项作为恢复ID进行检查):

struct Tabs {
    static let Humans = "Humans"
    static let Robots = "Robots"
}
setTabById(id: Tabs.Robots)

请注意,我的tabController链接到导航控制器后面的视图控制器。如果没有导航控制器,它会像这样:
if controller.restorationIdentifier == id {

0

AppDelegate.m 文件中使用:

(void)tabBarController:(UITabBarController *)tabBarController
 didSelectViewController:(UIViewController *)viewController
{

     NSLog(@"Selected index: %d", tabBarController.selectedIndex);

    if (viewController == tabBarController.moreNavigationController)
    {
        tabBarController.moreNavigationController.delegate = self;
    }

    NSUInteger selectedIndex = tabBarController.selectedIndex;

    switch (selectedIndex) {

        case 0:
            NSLog(@"click me %u",self.tabBarController.selectedIndex);
            break;
        case 1:
            NSLog(@"click me again!! %u",self.tabBarController.selectedIndex);
            break;

        default:
            break;

    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接