Search code examples
iphoneobjective-cuitabbar

tabBarItem image and text not showing on UITableViewController


I just created a new iPhone tabbed Application using xcode project template, without storyboard. I deleted the FirstViewController and SecondViewController which was generated by the project template.

Later, I created new controllers called MyFirstViewController (subclass of UITableViewController) and MySecondViewController (subclass of UIViewController) and put them under UINavigationControllers

I changed the code a bit so now it looks like below:

appdelegate.m :

#import "MyFirstViewController.h"
#import "MySecondViewController.h"

....

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    //create view controllers
    UITableViewController * vc1 = [[MyFirstViewController alloc] initWithNibName:nil bundle:nil];
    UIViewController * vc2 = [[MySecondViewController alloc] initWithNibName:nil bundle:nil];

    //create navigation controllers
    UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:vc1];
    UINavigationController *nav2 = [[UINavigationController alloc] initWithRootViewController:vc2];

    //add nav controllers to tab bar controller
    self.tabBarController = [[UITabBarController alloc] init];
    self.tabBarController.viewControllers = @[nav1, nav2];
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];

    return YES;
}

tabBarItem is NOT SHOWING on first tab

MyFirstViewController.m :

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Setting tabbar item and image here is not showing. It just show empty tab, no title and no image. why o why?
        self.tabBarItem.image = [UIImage imageNamed:@"someImage"];
        self.tabBarItem.title = @"someName";        
    }
    return self;
}

but the second tab is working just well

MySecondViewController.m :

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // This is showing just fine
        self.tabBarItem.image = [UIImage imageNamed:@"someImage"];
        self.tabBarItem.title = @"someName";
    }
    return self;
}

Any idea why a subclass of UITableViewController can't show the tabBarItem? meanwhile UIViewController can show it just fine.


Solution

  • In your didFinishLaunchin method you have

    UITableViewController * vc1 = [[MyFirstViewController alloc] initWithNibName:nil bundle:nil];
    

    But in your MyFirstViewController you

    - (id)initWithStyle:(UITableViewStyle)style;
    

    You need to call this method instead on initWithNibName, as this method doesn't exist your tabBarItem is not showing up.