Last active
August 16, 2018 08:52
-
-
Save radianttap/4455176 to your computer and use it in GitHub Desktop.
Inserting child controllers in the Auto-Layout world.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ## inserting. this can be done in viewDidLoad | |
// this can be any view, here I'm adding to main view | |
UIView *containerView = self.view; | |
// load child controller | |
UIViewController *svc = [[UIViewController alloc] initWithNibName:nil bundle:nil]; | |
// kill the randomness | |
svc.view.translatesAutoresizingMaskIntoConstraints = NO; | |
// add child VC to hierarchy | |
[self addChildViewController:svc]; | |
// set initial rect | |
svc.view.frame = containerView.bounds; | |
// finally add the view | |
[containerView addSubview:svc.view]; | |
// now that child view is in, set constraints, as needed | |
NSDictionary *vd = @{@"svc" : svc.view}; | |
[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-0-[svc]-0-|" options:0 metrics:nil views:vd]]; | |
[containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[svc]-0-|" options:0 metrics:nil views:vd]]; | |
// bring subview to front, or where needed | |
[containerView bringSubviewToFront:svc.view]; | |
// finish up | |
[svc didMoveToParentViewController:self]; | |
// ## removing, same as before | |
[svc willMoveToParentViewController:nil]; | |
[svc.view removeFromSuperview]; | |
[svc removeFromParentViewController]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I don't think you need to set the frame of the view, that is not a recommended practice for auto-layouts anyway