Skip to content

Instantly share code, notes, and snippets.

@giln
Created May 6, 2019 14:03
Show Gist options
  • Save giln/203c7a00828c96cce1f999977e4ffb2a to your computer and use it in GitHub Desktop.
Save giln/203c7a00828c96cce1f999977e4ffb2a to your computer and use it in GitHub Desktop.
import UIKit
/// Extension used to facilitate adding child viewControllers in a viewController
public extension UIViewController {
/// Embeds a view controller and also adds it's view in the view hierarchay
///
/// - Parameter viewController: ViewController to add
func add(asChildViewController viewController: UIViewController, anchored: Bool = true, subview: UIView? = nil) {
let someView: UIView = subview ?? view
// Add Child View Controller
addChild(viewController)
// Add Child View as Subview
someView.addSubview(viewController.view)
if anchored {
// Embeded viewControllers should not use safeAnchors
someView.anchor(view: viewController.view, useSafeAnchors: false)
}
// Notify Child View Controller after
viewController.didMove(toParent: self)
}
/// Removes a view controller from both view controller and view hierachies
///
/// - Parameter viewControllerToRemove: ViewController to remove
func remove(viewControllerToRemove: UIViewController?) {
guard let viewController = viewControllerToRemove else {
return
}
// Notify Child View Controller before
viewController.willMove(toParent: nil)
// Remove View
viewController.view.removeFromSuperview()
// Remove ViewController
viewController.removeFromParent()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment