Search code examples
iosobjective-ccocoauitabbar

How to programmatically link UITabBar with Different ViewControllers with NIBs when UITabBar is NOT rootViewController


I have a tableViewController that once tapped on a cell it takes you to FirstViewControllerFirstViewController has a UITabBar with 4 items. I want to programmatically hook each of those buttons/items to viewController that already exist in my project.

I have done a lot of research but haven't arrived at something that address this problem

What I have so far is FirstViewController, SecondViewController, ThirdViewController, FourthViewController

in FirstViewController.xib I have the TabBar with 4 icons.

FirstViewController.h

@property (strong, nonatomic) IBOutlet UITabBarController *tabBarController;
@property (weak, nonatomic) IBOutlet UITabBarItem *tabBar;
@property (weak, nonatomic) IBOutlet UITabBarItem *firstItem;
@property (weak, nonatomic) IBOutlet UITabBarItem *secondItem;
@property (weak, nonatomic) IBOutlet UITabBarItem *thirdItem;
@property (weak, nonatomic) IBOutlet UITabBarItem *fourthItem;

FirstViewController.m

- (void)viewDidLoad {
    FirstViewController *first = [[FirstViewController alloc] init];
    SecondViewController *second = [[SecondViewController alloc] init];
    ThirdViewController *third = [[ThirdViewController alloc] init];
    FourthViewController *fourth = [[FourthViewController alloc] init];

    self.tabBarController.viewControllers = [NSArray arrayWithObject: first, second, third, fourth, nil];

}

This code doesn't work when I tab on the fourth button for example it doesn't show the fourthViewController nib


Solution

  • Assuming each UIViewController subclass has an associated .xib (nib) then use the designated initialiser.

    Instead of [[FirstViewController alloc] init] use initWithNibName:bundle: for each respective view controller instead.

    example -

    [[FirstViewController alloc] initWithNibName:@"nameOfNibFile" bundle:nil];