Skip to content

Instantly share code, notes, and snippets.

@tomohisa
Created June 8, 2012 19:20
Show Gist options
  • Star 69 You must be signed in to star a gist
  • Fork 16 You must be signed in to fork a gist
  • Save tomohisa/2897676 to your computer and use it in GitHub Desktop.
Save tomohisa/2897676 to your computer and use it in GitHub Desktop.
Add and Remove ChildViewController
// add child view
UIViewController* controller = [self.storyboard instantiateViewControllerWithIdentifier:@"test"];
[self addChildViewController:controller];
controller.view.frame = CGRectMake(0, 44, 320, 320);
[self.view addSubview:controller.view];
[controller didMoveToParentViewController:self];
// remove child view
UIViewController *vc = [self.childViewControllers lastObject];
[vc.view removeFromSuperview];
[vc removeFromParentViewController];
@caiguo37
Copy link

You should call [vc willMoveToParentViewController:nil]; before removeFromSuperview;

UIViewController *vc = [self.childViewControllers lastObject];
[vc willMoveToParentViewController:nil];
[vc.view removeFromSuperview];
[vc removeFromParentViewController];

@jalopezsuarez
Copy link

Thanks! your code is perfect...

@aamershahzad2
Copy link

i am facing a problem with child view controller. after navigation self.childViewControllers is going to null and that view cant remove from super view . any idea ?

@PhilippeBoisney
Copy link

Thanks a lot !! This helps me a lot :) 👍

@ekzn
Copy link

ekzn commented Feb 22, 2016

Also make sure to assign nil to child view controller after removing

@iChenwin
Copy link

iChenwin commented Nov 8, 2016

thanks! you saved my day.
I missed UIViewController *vc = [self.childViewControllers lastObject];

@brightfuture
Copy link

brightfuture commented Dec 29, 2016

In Swift 3:

Add child view

    let controller = storyboard?.instantiateViewController(withIdentifier: "test") as! UIViewController
    self.addChildViewController(controller)
    controller.view.frame = CGRect(0, 44, 320, 320)
    self.view.addSubview(controller.view)
    controller.didMove(toParentViewController: self)

Remove child view

    let vc = self.childViewControllers.last
    vc.removeFromSuperview()
    vc.removeFromParentViewController()

I work hard on helping more people when I'm helped :)

@MarkDKoslow
Copy link

vc.view.removeFromSuperview()*

@skander300
Copy link

I applied the solution but what to do if i want to add a childViewController that's embedded in a navigation controller (the navigation bar won't appear !!).
and thanks in advance.

@snowden2
Copy link

Thanks a lot. It works like a charm

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment