Search code examples
iosobjective-cios7ios8

adding view controller as child view in ios


Hi i am trying to add a view controller as a child view. and later remove this view controller form parent view.I am using following code for this purpose.

 self.loginView = [self.storyboard instantiateViewControllerWithIdentifier:@"LOGIN"];
 [self.view addSubview:self.loginView.view];

This code works fine for iOS8 but in iOS7 this code is not working it shows the half of the screen.On half part login is shown.

What could be the solution for this??


Solution

  • Add a custom UIView object in your main view (in XIB) in which you want to add and show your child view controller. Let contentView is the name of that view. Use following code to add child view controller:

    self.loginView = [self.storyboard instantiateViewControllerWithIdentifier:@"LOGIN"];
    [self addChildViewController:self.loginView];
    [self.loginView.view setFrame:CGRectMake(0.0f, 0.0f, self.contentView.frame.size.width, self.contentView.frame.size.height)];
    [self.contentView addSubview:self.loginView.view];
    [self.loginView didMoveToParentViewController:self]; 
    

    if you don't add last line, your child view controller will not receive events. By using this code you can simultaneously receive events in both parent and child view controllers.