Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add UINavigationController inside UIViewController

I have a UIViewController with a UIToolbar (on bottom) and I want to add a UINavigationController with UINavigationBar inside. But the UINavigationController is not displayed.

MyViewController.m :

- (void)viewDidLoad
{
    [super viewDidLoad];

    int toolBarHeight = 44;
    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, [self.view bounds].size.height-toolBarHeight, [self.view bounds].size.width, toolBarHeight)];

    UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh target:nil action:nil];
    toolBar.items = @[button];

    [self.view addSubview:toolBar];

    MyNavigationController *myNav = [[MyNavigationController alloc] init];

    [self addChildViewController:myNav];
}
like image 640
Sony Avatar asked Jul 22 '13 01:07

Sony


People also ask

Is UINavigationController a UIViewController?

A UINavigationController does a lot of this tedious work for you. As mentioned, it contains a stack of UIViewControllers. It will create a navigation bar at the top that will allow you to easily go back up the hierarchy of view controllers.

What is UINavigationController?

Overview. A navigation controller is a container view that can manage the navigation of hierarchical contents. The navigation controller manages the current displaying screen using the navigation stack. Navigation stack can have “n” numbers of view controllers.


2 Answers

Adding a view controller as a child view controller isn't enough. You also need to add the navigation controller's view as a subview of the container view controller's view.

[myNav willMoveToParentViewController:self];
myNav.view.frame = navFrame;  //Set a frame or constraints
[self.view addSubview:myNav.view];
[self addChildViewController:myNav];
[myNav didMoveToParentViewController:self];

See the View Controller Programming Guide for more details.

like image 118
architectpianist Avatar answered Oct 13 '22 01:10

architectpianist


For swift 5

let childNavController = UINavigationController()
parrentVC.addChild(childNavController)
parrentVC.view.addSubview(childNavController.view)
//Add constraints or frame for childNavController here.
childNavController.didMove(toParent: parrentVC)
    
like image 31
Oleh H Avatar answered Oct 12 '22 23:10

Oleh H