Reputation: 51
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
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.
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
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