I am trying to programmatically switch the tab bar item. The following code works fine, but I can't get it to work in certain situations:
self.tabBarController.selectedIndex = 0;
Here is the problem:
I have a tab bar controller with two UIViewController classes. In the second tab, I have the code above placed inside an if statement within the viewWillAppear method. The code above itself works, but it only works if the view has never been loaded. So, on the first tab I have a button. When that button is pushed, I programmatically switch to the second tab. At that point my code works, and I essentially stay on the first tab. But the switching doesn't work after that first time. It also doesn't work if I select that second tab before I press that button. The IF statement that my code is inside fires, but the selected tab doesn't change.
Any help would be appreciated. Please don't hesitate to ask for clarification if you need it.
Thanks!
Let me add more information:
(1) This is only used on rare occassion. The first screen is a search screen. After you press search, you are taken to the second tab automatically, unless there are no results, then you are alerted and you stay there.
(2) The second tab maintains a list of either all items, if no search to narrow down has been performed, or the the list of narrowed down items. Either way, that list is always available. So even though I stop them on the search page, if they forget and click the other tab, they will be informed there are no items. At this point I would like to bring them back to tab one, as a convience only.
It's not THAT big of a deal, I can live without it, and it's not the horrible programming scheme that some are making it out to be. I just wanted to add that one user convienence item ...
Thanks to tc! I used the following method in my UITabBarControllerDelegate:
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
if(self.tabBarController.selectedIndex == 0){
if([books count] == 0){
[self alertNoResults];
return(FALSE);
}
}
return(TRUE);
}
Worked like a charm!