Created
May 6, 2019 14:03
-
-
Save giln/203c7a00828c96cce1f999977e4ffb2a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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