Fred Collins Fred Collins - 1 year ago 195
Objective-C Question

Add child view controller to UINavigationController

I'm trying to add a child view controller to a

contained in a
with this code:

- (void)buttonTapped:(id)sender
MyChildController *viewController = [self.storyboard instantiateViewControllerWithIdentifier:@"MyChild"];
[self addChildViewController:viewController];
[self.view addSubview:viewController.view];
[viewController didMoveToParentViewController:self];

viewController.view.alpha = 0.0f;
[UIView animateWithDuration:0.4 animations:^{
viewController.view.alpha = 1.0f;

But this is the result:

Image Result

As you can see the
and the
are still on top of the child view controller. How can I put the child view controller on top of all? I've already tried to replace the code with:

[self.navigationController addChildViewController:viewController];
[self.navigationController.view addSubview:viewController.view];
[viewController didMoveToParentViewController:self.navigationController];

But in this way the
of the
doesn't get called, dunno why.

Answer Source

In your first view controller, do something like this:

- (IBAction)buttonClick:(id)sender
    SecondViewController *secondView = [self.storyboard instantiateViewControllerWithIdentifier:@"SecondViewController"];
    UIImage *blurryImage = [UIImage imageNamed:@"foo.jpeg"];
    secondView.imageView.image = blurryImage;
    [self.navigationController addChildViewController:secondView];
    secondView.view.frame = self.navigationController.view.frame;
    [self.navigationController.view addSubview:secondView.view];

Then in your second view controller, add the getter for your imageview:

-(UIImageView *)imageView
    if( _imageView == nil )
        _imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 548)];
        [self.view addSubview:_imageView];
    return _imageView;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download