Created
June 6, 2018 08:40
-
-
Save neoneye/fd01d21944b40fc7794af6c8f0591725 to your computer and use it in GitHub Desktop.
Install child view controller
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
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