Skip to content

Instantly share code, notes, and snippets.

@fethica
Last active March 3, 2020 18:54
Show Gist options
  • Save fethica/3c3180837de9693858e70b5c2d374357 to your computer and use it in GitHub Desktop.
Save fethica/3c3180837de9693858e70b5c2d374357 to your computer and use it in GitHub Desktop.
extension UIViewController {
func embed(_ child: UIViewController, animated: Bool = false) {
let duration = animated ? 0.3 : 0.0
child.view.alpha = 0
child.willMove(toParent: self)
self.addChild(child)
self.view.addSubview(child.view)
child.view.translatesAutoresizingMaskIntoConstraints = false
self.view.topAnchor.constraint(equalTo: child.view.topAnchor).isActive = true
self.view.bottomAnchor.constraint(equalTo: child.view.bottomAnchor).isActive = true
self.view.leadingAnchor.constraint(equalTo: child.view.leadingAnchor).isActive = true
self.view.trailingAnchor.constraint(equalTo: child.view.trailingAnchor).isActive = true
self.view.setNeedsLayout()
self.view.layoutIfNeeded()
UIView.animate(withDuration: duration, animations: {
child.view.alpha = 1
}) { (completed) in
child.didMove(toParent: self)
}
}
func unembed(_ child: UIViewController, animated: Bool = false) {
child.willMove(toParent: nil)
let duration = animated ? 0.3 : 0.0
UIView.animate(withDuration: duration, animations: {
child.view.alpha = 0
}) { (completed) in
child.view.removeFromSuperview()
child.removeFromParent()
child.didMove(toParent: nil)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment