We can add a ChildViewController using container by following code.
-(void)addChildViewController{
UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
NSString *strClass = NSStringFromClass([YourChildViewController class]);
YourChildViewController *vc = [sb instantiateViewControllerWithIdentifier:strClass];
if (self.childViewControllers.count > 0 ) //check if container already has any ChildViewcontroller
{
// replace it with another child controller.
[self swapFromViewController:[self.childViewControllers objectAtIndex:0] toViewController:vc];
}
else
{
// else add ChildViewController to container.
[self addChildControllerForFirstTime:vc];
}
}
// To swap child controller
- (void)swapFromViewController:(UIViewController *)fromViewController toViewController:(UIViewController *)toViewController
{
toViewController.view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[fromViewController willMoveToParentViewController:nil];
[self addChildViewController:toViewController];
[self transitionFromViewController:fromViewController toViewController:toViewController duration:0.2 options:UIViewAnimationOptionTransitionCrossDissolve animations:nil completion:^(BOOL finished) {
[fromViewController removeFromParentViewController];
[toViewController didMoveToParentViewController:self];
}];
}
//To add child controller
- (void)addChildControllerForFirstTime:(UIViewController*)vc{
[self addChildViewController:vc];
((UIViewController *)vc).view.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
[self.view addSubview:((UIViewController *)vc).view];
[vc didMoveToParentViewController:self];
}
0 Comment(s)