【问题标题】:Selecting a tab bar item conditionally有条件地选择标签栏项目
【发布时间】:2013-11-11 07:37:41
【问题描述】:

我想以编程方式从 UITabBarItem 中选择一个选项卡。 我对如何做到这一点进行了一些研究,得到的答案如下:

  [self.parentViewController.tabBarController setSelectedIndex:2];

但是,它不起作用。我没有从 viewDidAppear 函数中调用它(正如 post 中所建议的那样,因为我需要有条件地在其他地方调用它。这段代码是否只在 viewDidAppear 函数中工作? 这是我的故事板的屏幕截图。 我从一个用红色圆圈标记的 viewController 调用它,我的 UITabBarController 用黄色圆圈标记。抱歉,图像质量不佳。 红圈类是“facebook 风格侧边栏菜单”实现的一部分。 我是iOS开发的新手,任何帮助将不胜感激。 非常感谢!

【问题讨论】:

  • 你使用 UITabBar 作为 rootViewController 吗?
  • 不,我使用 UINavigationController 作为 rootViewController,然后我有一个与该 UINavigationController 有关系的 UITabBarController。
  • 您可以从任何可以访问标签控制器的地方调用标签控制器上的setSelectedIndex: 方法。
  • 试试这个[self.tabBarController setSelectedIndex:2];
  • 是的,您可以在任何地方使用 setSelectedIndex,它应该可以正常工作。请更详细地解释您的情况。

标签: ios


【解决方案1】:

最佳实践是,每当您在应用程序中使用 UITabBar 时,将您的应用程序设计为使用 UITabBar 作为 rootViewController。您可以通过编码有条件地选择tabItem

[self.tabBarController setSelectedIndex:1];

这在任何地方都可以工作。

【讨论】:

  • 这是否意味着我不需要 UINavigationController?我不能把它作为 rootViewController,唯一的选择是关系 segues 或 push 和 modal。这是否意味着我在其他部分做错了什么?提前谢谢你。
  • 为什么你使用 UINavigationController 作为 rootViewController?,根据截图,你又在 UITabBar 中调用 UINavigationController 的视图。
  • 我想每次我们使用UITabBarController的时候,我们需要一个UINavigationController在ViewController之前作为rootViewController。我无法将 UITabBar 设置为 rootViewController,只能使用“relationship segues”或 push/modal/custom。
  • 嘿,代码有效,我接受了您的回答,因为由于您的回答,我对 rootViewController 以及我在哪里调用/访问我的 tabBarController 以调用 setSelectedIndex 进行了更多调查。我最后做的是在我的故事板中找到我的 tabBarController,然后在那个上调用 setSelectedIndex。谢谢
【解决方案2】:

试试这个

如果你的 UITabBarController 作为 rootViewController

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate.tabBarController setSelectedIndex:2];

【讨论】:

猜你喜欢
  • 2020-08-13
  • 2011-11-21
  • 2017-04-08
  • 2012-11-06
  • 1970-01-01
  • 2011-12-22
  • 1970-01-01
  • 2014-06-21
  • 1970-01-01
相关资源
最近更新 更多