Let\'s say I have a UIButton
in one tab view in my iPhone app, and I want to have it open a different tab in the tab bar of the TabBarController
.
For cases where you may be moving the tabs, here is some code.
for ( UINavigationController *controller in self.tabBarController.viewControllers ) {
if ( [[controller.childViewControllers objectAtIndex:0] isKindOfClass:[MyViewController class]]) {
[self.tabBarController setSelectedViewController:controller];
break;
}
}
Use in AppDelegate.m
file:
(void)tabBarController:(UITabBarController *)tabBarController
didSelectViewController:(UIViewController *)viewController
{
NSLog(@"Selected index: %d", tabBarController.selectedIndex);
if (viewController == tabBarController.moreNavigationController)
{
tabBarController.moreNavigationController.delegate = self;
}
NSUInteger selectedIndex = tabBarController.selectedIndex;
switch (selectedIndex) {
case 0:
NSLog(@"click me %u",self.tabBarController.selectedIndex);
break;
case 1:
NSLog(@"click me again!! %u",self.tabBarController.selectedIndex);
break;
default:
break;
}
}
I wanted to be able to specify which tab was shown by class rather than index as I thought it made for a robust solution that was less dependant on how you wire up IB. I didn't find either Disco's or Joped's solutions to work so i created this method:
-(void)setTab:(Class)class{
int i = 0;
for (UINavigationController *controller in self.tabBarContontroller.viewControllers){
if ([controller isKindOfClass:class]){
break;
}
i++;
}
self.tabBarContontroller.selectedIndex = i;
}
you call it like this:
[self setTab:[YourClass class]];
Hope this is helpful to someone
Note that the tabs are indexed starting from 0. So the following code snippet works
tabBarController = [[UITabBarController alloc] init];
.
.
.
tabBarController.selectedViewController = [tabBarController.viewControllers objectAtIndex:4];
goes to the fifth tab in the bar.
You can simply just set the selectedIndex
property on the UITabBarController to the appropriate index and the view will be changed just like the user tapped the tab button.
Try this code in Swift or Objective-C
Swift
self.tabBarController.selectedIndex = 1
Objective-C
[self.tabBarController setSelectedIndex:1];