Search code examples
iosobjective-cuitabbarcontrolleruitabbaruitabbaritem

Setting titles programmatically in a UITabBarController


Working with UITabBarController, I am facing the following issue. I want to have a given string as the title for all my view controllers, in each tab. This is apparently not possible to set within the storyboard.

By searching the net I have found this almost-working solution. Putting the following type of code in each of the separate view controllers.

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UITabBarItem *tabBarItem;
    tabBarItem=[[UITabBarItem alloc] initWithTitle:nil
                                             image:[self imageFromText:@"My Tab Title"
                                                              withFont:[UIFont systemFontOfSize:17.0]] tag:0];
    self.tabBarItem=tabBarItem;
}

The problem is: all the title are only set to what I want only when the user has tapped all the tabs.

This of course is not a good permanent solution. I need to have all the titles appear properly when the app starts.


Solution

  • You can change it in the AppDelegate.

    e.g. if you have 3 TabBarIcons:

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
       UITabBarController *tabBarController = (UITabBarController *)self.window.rootViewController;
    
        [[tabBarController.viewControllers objectAtIndex:0] setTitle:@"Your "];
        [[tabBarController.viewControllers objectAtIndex:1] setTitle:@"title "];
        [[tabBarController.viewControllers objectAtIndex:2] setTitle:@"here"];
    
        [[[tabBarController.viewControllers objectAtIndex:0] tabBarItem] setImage:[[UIImage imageNamed:@"first"] imageWithRenderingMode:UIImageRenderingModeAutomatic]];
        [[[tabBarController.viewControllers objectAtIndex:1] tabBarItem] setImage:[[UIImage imageNamed:@"second"] imageWithRenderingMode:UIImageRenderingModeAutomatic]];
        [[[tabBarController.viewControllers objectAtIndex:2] tabBarItem] setImage:[[UIImage imageNamed:@"third"] imageWithRenderingMode:UIImageRenderingModeAutomatic]];
    
        return YES;
    }