Skip to content

Instantly share code, notes, and snippets.

@neoneye
Created June 6, 2018 08:40
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 neoneye/fd01d21944b40fc7794af6c8f0591725 to your computer and use it in GitHub Desktop.
Save neoneye/fd01d21944b40fc7794af6c8f0591725 to your computer and use it in GitHub Desktop.
Install child view controller
import UIKit
extension UIViewController {
/// Taken from this great StackOverflow post by Phani Sai: https://stackoverflow.com/a/35473300/78336
func configureChildViewController(_ childController: UIViewController, onView: UIView?) {
var holderView = self.view
if let onView = onView {
holderView = onView
}
addChildViewController(childController)
holderView?.addSubview(childController.view)
holderView?.constrainViewEqual(childController.view)
childController.didMove(toParentViewController: self)
}
}
extension UIView {
fileprivate func constrainViewEqual(_ view: UIView) {
view.translatesAutoresizingMaskIntoConstraints = false
let pinTop = NSLayoutConstraint(item: view, attribute: .top, relatedBy: .equal,
toItem: self, attribute: .top, multiplier: 1.0, constant: 0)
let pinBottom = NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal,
toItem: self, attribute: .bottom, multiplier: 1.0, constant: 0)
let pinLeft = NSLayoutConstraint(item: view, attribute: .left, relatedBy: .equal,
toItem: self, attribute: .left, multiplier: 1.0, constant: 0)
let pinRight = NSLayoutConstraint(item: view, attribute: .right, relatedBy: .equal,
toItem: self, attribute: .right, multiplier: 1.0, constant: 0)
self.addConstraints([pinTop, pinBottom, pinLeft, pinRight])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment