Skip to content

Instantly share code, notes, and snippets.

@danielgarbien
Last active October 20, 2016 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielgarbien/38aa3b869a135f9b0f2d7cb1e51f0276 to your computer and use it in GitHub Desktop.
Save danielgarbien/38aa3b869a135f9b0f2d7cb1e51f0276 to your computer and use it in GitHub Desktop.
import UIKit
extension UIViewController {
/**
Add childController with no transition.
Embeds its view in container.
Calls didMove(toParentViewController:) on childController at a last step.
*/
func addImmediately(childController: UIViewController, embeddedIn container: UIView) {
addChildViewController(childController)
container.embed(subview: childController.view)
childController.didMove(toParentViewController: self)
}
func removeImmediatelyFromParentViewController() {
willMove(toParentViewController: nil)
view.removeFromSuperview()
removeFromParentViewController()
}
}
extension UIView {
func embed(subview: UIView) {
addSubview(subview)
subview.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate(
NSLayoutConstraint.constraints(for: subview, withEqualFrameAs: self))
}
}
extension NSLayoutConstraint {
static func constraints(for item: AnyObject, withEqualFrameAs otherItem: AnyObject) -> [NSLayoutConstraint] {
return constraints(
for: item,
otherItem: otherItem,
equalAttributes: [.left, .right, .top, .bottom])
}
static func constraints(for item: AnyObject, otherItem: AnyObject, equalAttributes: [NSLayoutAttribute]) -> [NSLayoutConstraint] {
return equalAttributes.map {
return self.init(item: item, attribute: $0, relatedBy: .equal, toItem: otherItem, attribute: $0, multiplier: 1, constant: 0)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment