Skip to content

Instantly share code, notes, and snippets.

@benaneesh
Created May 26, 2016 14:26
Show Gist options
  • Save benaneesh/d2c635d9010c89098e769460dbc319f5 to your computer and use it in GitHub Desktop.
Save benaneesh/d2c635d9010c89098e769460dbc319f5 to your computer and use it in GitHub Desktop.
/* add */
let childController = MyViewController()
addChildViewController(childController)
childController.view.frame = view.frame // or any other frame
view.addSubview(childController.view)
childController.didMoveToParentViewController(self)
/* remove */
if let childController = childViewControllers.last {
childController.willMoveToParentViewController(nil)
childController.view.removeFromSuperview()
childController.removeFromParentViewController()
}
/* faster way */
extension UIViewController {
func configureChildViewController(childController: UIViewController, onView: UIView?) {
let holderView: UIView = onView ?? self.view
addChildViewController(childController)
holderView.addSubview(childController.view)
constrainViewEqual(holderView, view: childController.view)
childController.didMoveToParentViewController(self)
}
func constrainViewEqual(holderView: UIView, view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
//pin 100 points from the top of the super
let pinTop = NSLayoutConstraint(item: view, attribute: .Top, relatedBy: .Equal,
toItem: holderView, attribute: .Top, multiplier: 1.0, constant: 0)
let pinBottom = NSLayoutConstraint(item: view, attribute: .Bottom, relatedBy: .Equal,
toItem: holderView, attribute: .Bottom, multiplier: 1.0, constant: 0)
let pinLeft = NSLayoutConstraint(item: view, attribute: .Left, relatedBy: .Equal,
toItem: holderView, attribute: .Left, multiplier: 1.0, constant: 0)
let pinRight = NSLayoutConstraint(item: view, attribute: .Right, relatedBy: .Equal,
toItem: holderView, attribute: .Right, multiplier: 1.0, constant: 0)
holderView.addConstraints([pinTop, pinBottom, pinLeft, pinRight])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment