user3883340
user3883340

Reputation: 51

Changing Tab bar programmatically

enter image description here

I have created tabbar in storyboard .and i am trying to change default tab bar programmatically using following code.

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

But its not working.How i can do it? its not working at all.

Also i want to go back to home view controller when user select first tab.how we can achieve this functionality.

Upvotes: 5

Views: 5809

Answers (2)

Mayank Jain
Mayank Jain

Reputation: 5754

You can change tab from programmatically:-

[self.tabBarController setSelectedIndex:1];

You can access tab bar's object from storyboard. In storyboard select tabBarController and set storyboard Id. Refer image.

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

Upvotes: 4

Esha
Esha

Reputation: 1303

From the current selected view controller you can change tab selected index using code below.

[self.tabBarController setSelectedIndex:1];

To add Tab bar controller to viewcontrollers hirarchy IF YOU ARE USING NAVIGATION AS BASE then you can use:

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

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

Upvotes: 4

Related Questions