How to change initial tab bar selection programmatically

10,683

Solution 1

Since this is the initial view controller, and is not a subclass, you need to set this in your appDelegate.

In AppDelegate.m, add the following to your application:didFinishLaunchingWithOptions: method:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.

    // Select the left-most tab of our initial tab bar controller:
    UITabBarController *tabBar = (UITabBarController *)self.window.rootViewController;
    tabBar.selectedIndex = 0;
    return YES;
}

Solution 2

tabBar setSelectedItem: try using this in your viewDidLoad

Share:
10,683
LazerLex
Author by

LazerLex

Updated on June 08, 2022

Comments

  • LazerLex
    LazerLex almost 2 years

    Having problems changing the initial tab bar selection on an application (i.e. the middle tab is selected on app launch rather than the leftmost tab). The app uses storyboards and the tab bar controller was added later on in development via the storyboard method.

    tabBarController.selectedIndex = 1;
    

    the above code doesn't work (because I don't have a custom view controller connected to my tab bar, just the default UITabBarController):

    Done some googling and looked at many different resources and haven't quite found a solution for an app that wasn't initially created using Apple's template Tab Bar Application.

  • LazerLex
    LazerLex almost 12 years
    that doesn't work because I don't have a specific view controller for my Tab Bar (with a viewDidLoad method). I don't have an outlet created for my tab bar. It's just the default created in Storyboards.
  • LazerLex
    LazerLex almost 12 years
    I added a view controller.h and .m and connected it with my TabBarController. I created a UITabBarController outlet and used selected index. and then tried what you said (creating a UITabBar outlet and using setSelectedItem) and still nothing :/
  • LazerLex
    LazerLex almost 12 years
    You're brilliant. Worked perfectly. Makes sense i'd have to do it in the AppDelegate because it's the initial view controller. Thanks.
  • lnafziger
    lnafziger almost 12 years
    For future reference, in the situation where you need to do something similar and it is not the initial view controller, you would over-ride prepareForSegue in the view which is before the one being loaded and set it from there.