UITabBarController: switch to a different view controller programmatically

Ionic Walrus picture Ionic Walrus · Jul 8, 2009 · Viewed 33.6k times · Source

In my iPhone app, to restore previously viewed tab, on launch I set the setSelectedIndex: (also tried setSelectedViewController: as per docs but to no avail)

This works on iPhone OS 3.0 - however on OS 2.x the selected index greater than 3 (the first 4 tabs) doesn't switch to the required view. This is documented by Apple here: http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UITabBarController_Class/Reference/Reference.html#//apple_ref/occ/instp/UITabBarController/selectedViewController

Im wondering if its possible to switch to a view controller under iPhone OS 2.x ? Any help is appreciated.

Btw on my simulator setting index greater than 3 throws an error (for iPhone OS 2.x) - so I have wrapped this in a @try{..} @catch(id ..){ } block - hope this technique helps someone.

Answer

user190302 picture user190302 · Oct 15, 2009

Maybe this will help. What I did was save the index of the tab bar item that was selected. When the app launches I check to see if the number is greater than 3, if it is I set the selected tab bar view controller to be the more navigation controller and then just push the saved index tab bar view controller from the more navigation controller.

if ([[WSFUserDefaults sharedInstance] savedTabBarLocation] > 0) {

            if ([[WSFUserDefaults sharedInstance] savedTabBarLocation] > 3) {
                UIViewController *selectViewController = [tabBarController.viewControllers objectAtIndex:[[WSFUserDefaults sharedInstance] savedTabBarLocation]];
                [tabBarController setSelectedViewController:tabBarController.moreNavigationController];
                [tabBarController.moreNavigationController popToRootViewControllerAnimated:NO];//make sure we're at the top level More
                [tabBarController.moreNavigationController pushViewController:selectViewController animated:NO];
            }
            else {
                [tabBarController setSelectedIndex:[[WSFUserDefaults sharedInstance] savedTabBarLocation]];
            }
        }