lambdas
lambdas

Reputation: 4088

Add controller to UITabBarController without new item appearing in the tab bar

I have an application with UITabBarController as its main controller.

When user taps a button(not in the tab bar, just some other button), I want to add new UIViewController inside my UITabBarController and show it, but I don't want for new UITabBarItem to appear in tab bar. How to achieve such behaviour?

I've tried to set tabBarController.selectedViewController property to a view controller that is not in tabBarController.viewControllers array, but nothing happens. And if I add view controller to tabBarController.viewControllers array new item automatically appears in the tab bar.

Update

Thanks to Levi, I've extended my tab bar controller to handle controllers that not present in .viewControllers.

@interface MainTabBarController : UITabBarController

/** 
 * By setting this property, tab bar controller will display
 * given controller as it was added to the viewControllers and activated
 * but icon will not appear in the tab bar.
 */
@property (strong, nonatomic) UIViewController *foreignController;

@end


#import "MainTabBarController.h"

@implementation MainTabBarController

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
  self.foreignController = nil;
}

- (void)setForeignController:(UIViewController *)foreignController
{
  if (foreignController) {
    CGFloat reducedHeight = foreignController.view.frame.size.height - self.tabBar.frame.size.height;
    foreignController.view.frame = CGRectMake(0.0f, 0.0f, 320.0f, reducedHeight);

    [self addChildViewController:foreignController];
    [self.view addSubview:foreignController.view];
  } else {
    [_foreignController.view removeFromSuperview];
    [_foreignController removeFromParentViewController];
  }

  _foreignController = foreignController;
}

@end

The code will correctly set "foreign" controller's view size and remove it when user choose item in the tab bar.

Upvotes: 5

Views: 4310

Answers (2)

Levi
Levi

Reputation: 7343

You either push it (if you have a navigation controller) or add it's view to your visible View Controller's view and add it as child View Controller also.

Upvotes: 2

Rui Peres
Rui Peres

Reputation: 25917

You can either present the new view controller with:

- (void)presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion;

Or, if one of your UIViewControllers is inside a UINavigationController, you can:

- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated;

Upvotes: 0

Related Questions