Skip to content

Instantly share code, notes, and snippets.

@stleamist
Last active February 23, 2020 08:57
Show Gist options
  • Save stleamist/63da4b9aed8a348aa4d75de8aed6632f to your computer and use it in GitHub Desktop.
Save stleamist/63da4b9aed8a348aa4d75de8aed6632f to your computer and use it in GitHub Desktop.
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