Created
May 3, 2020 09:34
-
-
Save michzio/502e348c881e1bb49f64cc8b954b0fcb to your computer and use it in GitHub Desktop.
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
class HostingControllerCollectionViewCell<Content: View> : UICollectionViewCell { | |
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 | |
contentView.addSubview(controller.view) | |
// constraint subview | |
NSLayoutConstraint.activate([ | |
controller.view.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor), | |
controller.view.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor), | |
controller.view.topAnchor.constraint(equalTo: self.contentView.topAnchor), | |
controller.view.bottomAnchor.constraint(equalTo: self.contentView.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