简体   繁体   中英

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.

您可以按下它(如果您有导航控制器),也可以将其视图添加到可见的View Controller视图中,并将其添加为子视图控制器。

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM