Skip to content

Instantly share code, notes, and snippets.

@orakaro
Created January 5, 2019 11:58
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 orakaro/9ba360c9906f705b51652b1a404affc9 to your computer and use it in GitHub Desktop.
Save orakaro/9ba360c9906f705b51652b1a404affc9 to your computer and use it in GitHub Desktop.
protocol UIComponent: class {
associatedtype Content: UIViewController
associatedtype Parent: UIViewController
var contentView: UIView { get }
var content: Content? { get set }
var parent: Parent? { get set }
}
extension UIComponent where Self: UIView {
func embed(content: Content, parent: Parent) {
self.content = content
self.parent = parent
content.view.translatesAutoresizingMaskIntoConstraints = false
if superview == nil {
content.willMove(toParent: parent)
} else {
parent.addChild(content)
}
contentView.addSubview(content.view)
NSLayoutConstraint.activate(
[
content.view.topAnchor.constraint(equalTo: contentView.topAnchor),
content.view.leftAnchor.constraint(equalTo: contentView.leftAnchor),
content.view.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
content.view.rightAnchor.constraint(equalTo: contentView.rightAnchor)
]
)
if superview == nil {
content.removeFromParent()
} else {
content.didMove(toParent: parent)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment