Set UITabBarItem title programmatically?

kheraud picture kheraud · Jun 15, 2011 · Viewed 8.3k times · Source

My app is based on a tab bar architecture. In order to have an easy internationalisation mechanic, I do not write any string in XIB files. viewdidload permits to change programmaticaly the strings in the views.

When my app launches, I can see the 4 tabs. But in fact only the first one loads its view controller. The others wait for user click to be loaded. Tabs title can be changed using [self setTitle:@"Mouhahaha"]; in viewDidLoad of loaded view controller.

If I want to keep my internationalisation mechanic available, I do not set in my XIB the name of tabbar items. But, as at start all tab' view controllers are not loaded, I have blank titles for some tabs. The right title is set only when the user click on the tab.

I am looking for a way to set this title programaticaly for each tabbaritem. Do you have hints ?

Thanks a lot.

kheraud

Answer

john.k.doe picture john.k.doe · Jun 21, 2012

my preferred method of doing this programmatically together with the storyboard is to make a subclass of UITabBarController, have my tab bar controller scene in my storyboard use the new subclass (with 3 UIViewController relationships from the tab bar controller to the desired view controller in the case below), and then override viewWillAppear:

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    NSArray* titleKeys = [NSArray arrayWithObjects:@"top places", 
                                                   @"localizablekey1",
                                                   @"localizablekey2",
                                                   @"localizablekey3",
                                                   nil];
    [super viewWillAppear:animated];
    int count = 0; for (UIViewController* viewController in self.viewControllers)
        viewController.tabBarItem.title = NSLocalizedString([titleKeys objectAtIndex:count++], nil);
}