I'm trying to create a container view controller using iOS5
and new methods like addChildViewController
.
Do I have to call addSubview
after calling addChildViewController
?
Do I have to call removeFromSuperview
before calling removeChildViewController
?
I don't see anything about this in Apple docs.
What do you think?
Short answer: "Yes, and yes." The view hierarchy and the view controller hierarchy are still independent. The containment API simply allows views from other controllers to present themselves within a parent controller's view in a clean and consistent way.
You can find a bit in Apple's docs here... this is a relevant passage from the "Container View Controllers Arrange Content of Other View Controllers" section:
A container manages a view hierarchy just as other view controllers do. A container can also add the views of any of its children into its view hierarchy. The container decides when such a view is added and how it should be sized to fit the container’s view hierarchy, but otherwise the child view controller remains responsible for the view and its subviews.
If you have access, I would highly recommend checking out the WWDC 2011 video entitled "Implementing UIViewController Containment" (watch in Safari | view in iTunes).
1) Do I have to call addSubview after calling addChildViewController?
Yes
2) Do I have to call removeFromSuperview before calling removeChildViewController?
Not quite
You should call removeFromParentViewController:
instead of removeChildViewController:
You should also call willMoveToParentViewController:
For adding / removing, you can refer to this great category :
UIViewController + Container
- (void)containerAddChildViewController:(UIViewController *)childViewController {
[self addChildViewController:childViewController];
[self.view addSubview:childViewController.view];
[childViewController didMoveToParentViewController:self];
}
- (void)containerRemoveChildViewController:(UIViewController *)childViewController {
[childViewController willMoveToParentViewController:nil];
[childViewController.view removeFromSuperview];
[childViewController removeFromParentViewController];
}
Official resource at developer.apple.com
Adding to Peter's answer:
one reason I found for calling addChildViewController
before addSubview
was that when addSubview
is called then the viewDidLoad
of the child get's called, and in some cases you will want to have the parent-child hierarchy properly set up at that point. If that isn't done, during child's the viewDidLoad the parentViewController property will be nil.