Skip to content

Instantly share code, notes, and snippets.

@radianttap
Last active August 16, 2018 08:52
Show Gist options
  • Save radianttap/4455176 to your computer and use it in GitHub Desktop.
Save radianttap/4455176 to your computer and use it in GitHub Desktop.
Inserting child controllers in the Auto-Layout world.
// ## 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];
@tabishfayyaz
Copy link

I don't think you need to set the frame of the view, that is not a recommended practice for auto-layouts anyway

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment