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

rot*_*ice 156 iphone objective-c uitabbarcontroller ios

假设UIButton我的iPhone应用程序中有一个标签视图,我想让它在标签栏中打开一个不同的标签TabBarController.我该如何编写代码来执行此操作?

我假设我卸载现有视图并加载特定的选项卡视图,但我不确定如何准确编写代码.

Jor*_*dan 393

在Swift或Objective-C中尝试此代码

迅速

self.tabBarController.selectedIndex = 1
Run Code Online (Sandbox Code Playgroud)

Objective-C的

[self.tabBarController setSelectedIndex:1];
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果索引映射到更多视图控制器中的选项卡(如果您有超过五个选项卡),则这将不起作用.在这种情况下,使用`-setSelectedViewController:`. (7认同)

Joh*_*ith 20

请注意,选项卡从0开始编制索引.因此,以下代码段有效

tabBarController = [[UITabBarController alloc] init];
.
.
.
tabBarController.selectedViewController = [tabBarController.viewControllers objectAtIndex:4];
Run Code Online (Sandbox Code Playgroud)

转到栏中的第五个标签.


小智 11

我的意见是,selectedIndex或者使用objectAtIndex不一定是切换标签的最佳方式.如果您重新排序选项卡,硬编码索引选择可能会破坏您之前的应用程序行为.

如果您有要切换到的视图控制器的对象引用,则可以执行以下操作:

tabBarController.selectedViewController = myViewController
Run Code Online (Sandbox Code Playgroud)

当然你必须确保,这myViewController确实在列表中tabBarController.viewControllers.


Ale*_*eem 9

您只需selectedIndex将UITabBarController上的属性设置为适当的索引,就可以像用户点击选项卡按钮一样更改视图.

  • 一个小的区别是没有调用可以通知用户切换标签的委托方法. (6认同)
  • 设置`selectedIndex`对我来说也不适用于索引> 4,但`selectedViewController`可以. (3认同)