Lorenz
Lorenz

Reputation: 775

Switching tabs programmatically not working properly

I'm trying to switch tabs programmatically using:

[tabBarController setSelectedIndex:index]

I've also tried:

tabBarController.selectedViewController = [tabBarController.viewControllers objectAtIndex:index];

It works the first time - switching both tabs and the view associated with the tab. However it doesn't work the second time and thereafter. Then it erratically switches the tab (not always), and doesn't switch the view controller associated with the tab.

Any ideas?

Here's what I'm trying to accomplish:

Tab A: I have a tab that launches the camera to take a picture and add some details.

Tab B: I have a tab with a list of pictures taken and a bar button to add a new item by taking a picture and adding details.

I'm trying to make it so that when the user taps Tab A it switches to Tab B and launches the add item method. What's the best way to do this?

Here is more detailed code:

Tab A is hooked up to navigation controller with a UIViewController. In that controller I have the following:

- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate switchView];
}

In AppDelegate.m I have the following:

- (void)switchView
{   
tabBarController = (UITabBarController *)self.window.rootViewController;
tabBarController.selectedViewController 
= [tabBarController.viewControllers objectAtIndex:3];
}

Upvotes: 1

Views: 1193

Answers (2)

Lorenz
Lorenz

Reputation: 775

It turns out the problem was that I was changing the tabBarController index from viewWillAppear instead of viewDidAppear. Must be something to do with the order in which things are loaded.

Upvotes: 2

MattyG
MattyG

Reputation: 8497

The UIViewController class has a tabbarController property, so you can simplify things by calling the view controller's parent controller (the tab bar controller) instead of using the app delegate to access the tab bar controller. Calling setSelectedIndex should be fine too. So from inside your view controller:

[self.tabbarController setSelectedIndex:3];

To help with debugging, you could put some NSLogs in relevant places:

NSLog(@"The currently selected tab is: %@",self.tabbarController.selectedIndex);

Upvotes: 2

Related Questions