Last active
February 23, 2020 08:57
-
-
Save stleamist/63da4b9aed8a348aa4d75de8aed6632f 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 | |
class ContainerViewController: UIViewController { | |
convenience init(contentViewController: UIViewController) { | |
self.init() | |
self.contentViewController = contentViewController | |
} | |
var contentViewController: UIViewController? { | |
didSet { | |
if let oldViewController = oldValue { | |
hideContent(viewController: oldViewController) | |
} | |
if let newViewController = contentViewController { | |
displayContent(viewController: newViewController) | |
} | |
} | |
} | |
private func displayContent(viewController: UIViewController) { | |
self.addChild(viewController) | |
self.view.addSubview(viewController.view) | |
viewController.view.translatesAutoresizingMaskIntoConstraints = false | |
NSLayoutConstraint.activate([ | |
viewController.view.topAnchor.constraint(equalTo: self.view.topAnchor), | |
viewController.view.bottomAnchor.constraint(equalTo: self.view.bottomAnchor), | |
viewController.view.leadingAnchor.constraint(equalTo: self.view.leadingAnchor), | |
viewController.view.trailingAnchor.constraint(equalTo: self.view.trailingAnchor) | |
]) | |
viewController.didMove(toParent: self) | |
} | |
private func hideContent(viewController: UIViewController) { | |
viewController.willMove(toParent: nil) | |
viewController.view.removeFromSuperview() | |
viewController.removeFromParent() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment