以编程方式更改选项卡栏

时间:2014-07-28 07:20:02

标签: ios storyboard

enter image description here

我在storyboard中创建了tabbar。我正在尝试使用以下代码以编程方式更改默认标签栏。

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Make sure your segue name in storyboard is the same as this line
    if ([[segue identifier] isEqualToString:@"TAB"])
    {
        UIStoryboard* storyboard   = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
        UITabBarController *tabBar = [storyboard instantiateViewControllerWithIdentifier:@"tabBar"];
        tabBar.selectedViewController = [tabBar.viewControllers objectAtIndex:1];
    }
}

但它不起作用。我怎么能这样做?它根本不起作用。

此外,我想在用户选择第一个标签时返回主视图控制器。我们可以实现此功能。

2 个答案:

答案 0 :(得分:4)

从当前选定的视图控制器,您可以使用下面的代码更改选项卡选择的索引。

[self.tabBarController setSelectedIndex:1];

将标签栏控制器添加到viewcontrollers hirarchy如果您使用导航为基础,则可以使用:

UIStoryboard* storyboard   = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
        UITabBarController *tabBar = [storyboard instantiateViewControllerWithIdentifier:@"tabBar"];
        tabBar.selectedViewController = [tabBar.viewControllers objectAtIndex:1];

[self.navigationController pushViewController:tabBar animated:BOOL];

答案 1 :(得分:4)

您可以通过编程方式更改标签: -

[self.tabBarController setSelectedIndex:1];

您可以从故事板访问标签栏的对象。在storyboard中选择tabBarController并设置故事板ID。参考图片。

enter image description here

UIStoryboard* storyboard   = [UIStoryboard storyboardWithName:@"Main" bundle:nil]; //please check your main storyboard name.
UITabBarController *tabBar = [storyboard instantiateViewControllerWithIdentifier:@"tabBar"];
tabBar.selectedViewController = [tabBar.viewControllers objectAtIndex:1];