To form a parent-child relationship:
- Send the
-addChildViewController:message to the parent with the child as the parameter. This will send the-willMoveToParentViewController:message to the child with the parent as the parameter. - Add the child view controller's
viewas a subview to the parent view controller'sview. - Send the
-didMoveToParentViewController:message to the child with the parent as the parameter.
For example,
[parent addChildViewController:child];
[parent.view addSubview:child.view];
[child didMoveToParentViewController:parent]
To break a parent-child relationship, simply send the -removeFromParentViewController message to the child after sending -willMoveToParentViewController:.
[child willMoveToParentViewController:nil];
[child.view removeFromSuperview];
[child removeFromParentViewController];To transition between child view controllers, say, for creating your own UINavigationController-like object:
- Make sure the destination view controller has been added as a child via the
-addChildViewController:message – transitioning between two view controllers requires both children to have the same parent. - Send the
-transitionFromViewController:toViewController:duration:options:animations:completion:message to the parent with yourfromandtoview controllers. This will handle adding and remove the view controllers' views from the parent's view hierarchy. - Within the
completionblock, send the-removeFromParentViewControllermessage to thefromview controller and the-didMoveToParentViewController:message to thetoview controller with the parent as the parameter.
For example,
[parent addChildViewController:toVC];
[parent transitionFromViewController:fromVC
toVC:toVC
duration:0.0
options:UIViewAnimationOptionTransitionNone
animations:nil
completion:^(BOOL finished) {
[fromVC willMoveToParentViewController:nil];
[fromVC removeFromParentViewController];
[toVC didMoveToParentViewController:parent];
}];
You need to call willMoveToParentViewController:nil when breaking a parent child relationship.