Skip to content

Instantly share code, notes, and snippets.

@drance
Last active September 2, 2021 00:26
Show Gist options
  • Save drance/5886813 to your computer and use it in GitHub Desktop.
Save drance/5886813 to your computer and use it in GitHub Desktop.
Tired of the UIViewController containment three-step. Adds a convenience param if the destination superview is not actually the parent VC's main view.
@implementation UIViewController (BHSContainment)
- (void)bhs_addChildViewController:(UIViewController *)child {
[self bhs_addChildViewController:child superview:self.view];
}
// Note this potentially forces view loads on both parent and child
// Not a problem if used in -viewDidLoad or later
// Use superview parameter with care. If it's not within the parent VC's hierarchy, you deserve to lose
- (void)bhs_addChildViewController:(UIViewController *)child superview:(UIView *)superview {
if (superview == nil) {
superview = self.view;
}
[self addChildViewController:child];
[superview addSubview:child.view];
[child didMoveToParentViewController:self];
}
- (void)bhs_removeChildViewController:(UIViewController *)child {
[child willMoveToParentViewController:nil];
if ([child isViewLoaded]) {
[child.view removeFromSuperview];
}
[child removeFromParentViewController];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment