Search code examples
iosuiviewcontrolleruitabbarcontrolleruisplitviewcontroller

UITabBarController.selectedIndex returning wrong value


I have a UITabBarController with two tabs. Each tab has the same UISplitViewController within itself. I want to see the value of selected index of tabbarcontroller to see which splitview is open right now insidethe MasterViewController in UITableViewDelegate method, but it returns me the wrong value. It always returns 0 even if the index 1 is selected.

In appdelegate, I have initialized both of them by the same code in a loop this way:

             MasterViewController *masterViewController = [[MasterViewController alloc] initWithNibName:@"MasterViewController_iPad" bundle:nil];

             UINavigationController *masterNavigationController = [[UINavigationController alloc] initWithRootViewController:masterViewController];

             detailViewController = [[DetailViewController alloc] initWithNibName:@"DetailViewController_iPad" bundle:nil];                 
             UINavigationController *detailNavigationController = [[UINavigationController alloc] initWithRootViewController:detailViewController];

             masterViewController.detailViewController = detailViewController;

             self.splitViewController = [[UISplitViewController alloc] init];
             splitViewController.tabBarItem = controller.tabBarItem;
             self.splitViewController.delegate = detailViewController;
             self.splitViewController.viewControllers = @[masterNavigationController, detailNavigationController];
             [controllers replaceObjectAtIndex:index withObject:splitViewController];

}

Any help would be largely appreciated! I think it might be some issue with the splitViewController because it works fine on iPhone.


Solution

  • My guess is, it is because your ViewController expects the TabBarController to be it's parentViewController. You could try checking self.splitViewController.tabBarController.selectedIndex.

    However, I would recommend you to use the SplitViewController as the root of your app, and put the TabBarController inside your master. You can achieve the same effect this way and it would be more correct. Hope this helps!

    Edit:

    According to the View Controller Catalog "A split view controller must always be the root of any interface you create. In other words, you must always install the view from a UISplitViewController object as the root view of your application’s window. The panes of your split view interface may then contain navigation controllers, tab bar controllers, or any other type of view controller you need to implement your interface. Split view controllers cannot be presented modally."

    So do not put it in a tab bar controller.