Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to add ChildViewController using container view in objc

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 374
    Comment on it

    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)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: