Last active
March 3, 2020 18:54
-
-
Save fethica/3c3180837de9693858e70b5c2d374357 to your computer and use it in GitHub Desktop.
This file contains 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
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