Add UINavigationController inside UIViewController

2019-03-27 13:24发布

问题:

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];
}

回答1:

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.