adding view controller as child view in ios

2019-03-01 07:10发布

问题:

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??

回答1:

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.



回答2:

Adding a UIViewController as a subView is not standard programming I believe, UIViewController is intended to handle a complete view on screen. Instead of adding a UIViewController to your UIView you should create a custom UIView and then use that UIView to achieve whatever results you want to.

EDIT : Use XIB to create a custom UIView.