Skip to content

Instantly share code, notes, and snippets.

@michzio
Created May 3, 2020 09:38
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 michzio/fadbe99658d12b5b438353227dfee81e to your computer and use it in GitHub Desktop.
Save michzio/fadbe99658d12b5b438353227dfee81e to your computer and use it in GitHub Desktop.
class HostingControllerCollectionReusableView<Content: View>: UICollectionReusableView {
var controller: UIHostingController<Content>?
func host(_ view: Content, parent: UIViewController? = nil) {
if let controller = controller {
controller.rootView = view
controller.view.layoutIfNeeded()
} else {
let controller = UIHostingController(rootView: view)
controller.view.translatesAutoresizingMaskIntoConstraints = false
controller.view.backgroundColor = .clear
self.controller = controller
// add child
parent?.addChild(controller)
// add subview
self.addSubview(controller.view)
// constraint subview
NSLayoutConstraint.activate([
controller.view.leadingAnchor.constraint(equalTo: self.leadingAnchor),
controller.view.trailingAnchor.constraint(equalTo: self.trailingAnchor),
controller.view.topAnchor.constraint(equalTo: self.topAnchor),
controller.view.bottomAnchor.constraint(equalTo: self.bottomAnchor)
])
// move to parent
if let parent = parent {
controller.didMove(toParent: parent)
}
controller.view.layoutIfNeeded()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment