通过编程方式更改选项卡栏

5

输入图像描述

我在故事版中创建了选项卡栏,现在我想使用以下代码通过编程方式更改默认选项卡栏。

- (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];
    }
}

但它没有起作用。我该怎么做?它根本不起作用。

另外,当用户选择第一个选项卡时,我想回到主页视图控制器。我们如何实现这个功能。


但它没有起作用? - Kumar KL
故事板和选项卡栏是对象吗? - Rajesh
prepareForSegue 在 segue 即将执行时被调用。 - toasted_flakes
2个回答

4
从当前选定的视图控制器,您可以使用以下代码更改选定的标签索引。
[self.tabBarController setSelectedIndex:1];

如果您的基础是导航,则可以使用以下方法将选项卡控制器添加到视图控制器层次结构中:

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

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

4
您可以通过编程来更改选项卡:-
[self.tabBarController setSelectedIndex:1];

您可以从Storyboard中访问选项卡栏的对象。在Storyboard中选择tabBarController并设置Storyboard 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];

1
当我使用这段代码时,它选择了第二个选项卡,但实际上它显示的是第一个视图的内容,我不知道哪里出了问题? - user3883340
请在您的tabBarController中添加viewControllers。 - Mayank Jain
我已经附上了我的故事板设计的图片,请看一下。 - user3883340

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