Search code examples
xcodeuinavigationcontrolleruitabbarcontrolleruitabbar

Setting tabBarController.selectedIndex/selectedViewController when it's a UINavigationController


I've got 5 views in my tabBarController and all of them are embedded in a separate navigationcontroller, i.e. every view has it's own navigationcontroller. I did this to make it easier to push segues, I know it's probably not the best solution but it works fine. Now to my question:

I'm trying to set the initial view with the following code:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    tabBarController.selectedIndex = 2;
    return YES;
}

However it's not working at all, the app simply starts and index 0 (the left most view).

I've searched through thorough threads like this and tried many different ways to solve this without any success...

Closest I got was when I in MainStoryboard_iPhone.storyboard checked the box "Is initial view controller" in the viewcontroller I want to start with. This way the I got the correct starting viewcontroller but the tabbar wasn't showing.


Solution

  • Since you're using storyboard, do this : 1) Give your tabBarController a storyboard identifier (say tbc); 2) In your appDelegate DidFinishLaunching, do this ::

    UITabBarController *tbc = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"tbc"];
    
    [tbc setSelectedIndex:1];
    [self.window setRootViewController:tbc];
    [self.window makeKeyAndVisible];
    
    return YES;
    

    PS : This is just one of many ways to make it work