Skip to content

Instantly share code, notes, and snippets.

@JoshuaKaden
Created May 23, 2019 15:29
Show Gist options
  • Save JoshuaKaden/84ef9eb86bd992f1da72e755193ad49a to your computer and use it in GitHub Desktop.
Save JoshuaKaden/84ef9eb86bd992f1da72e755193ad49a to your computer and use it in GitHub Desktop.
Extension for convenient UIViewController parenting
//
// UIViewController+Parenting.swift
//
// Created by Kaden, Joshua on 5/23/19.
//
import UIKit
extension UIViewController {
/// Removes all child view controllers by calling the appropriate methods.
///
/// The children's `willMove(toParent: nil)` methods are called.
/// Their views are also removed from the view hierarchy. Finally, their
/// `removeFromParent` methods are called.
func abandonChildrenViewControllers() {
children.forEach { $0.leaveParentViewController() }
}
/// Tells the view controller to add the supplied view controller as a child, by calling the appropriate methods.
///
/// This convenience method calls `addChild`, adds the child
/// view controller's view to the view hierarchy, and calls the child's
/// `didMove(toParent)` method.
///
/// The child view controller's view is added to the view hierarchy,
/// either to the main view, or the `targetView` (if supplied).
///
/// - Parameters:
/// - childController: The view controller to be added as a child.
/// - targetView: (optional) The child view controller's view will be added to this view.
func adoptChildViewController(_ childController: UIViewController, targetView: UIView? = nil) {
addChild(childController)
if let targetView = targetView {
targetView.addSubview(childController.view)
} else {
view.addSubview(childController.view)
}
childController.didMove(toParent: self)
}
/// Tells a child view controller to remove itself from its parent, by calling the appropriate methods.
///
/// The child's `willMove(toParent: nil)` method is called.
/// Its view is also removed from the view hierarchy. Finally, its
/// `removeFromParent` method is called.
func leaveParentViewController() {
willMove(toParent: nil)
view.removeFromSuperview()
removeFromParent()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment