Skip to content

Instantly share code, notes, and snippets.

@ice-cream-coder
Created February 22, 2021 21:29
Show Gist options
  • Save ice-cream-coder/dadfc341f9da60eac1522788cd9bc3ab to your computer and use it in GitHub Desktop.
Save ice-cream-coder/dadfc341f9da60eac1522788cd9bc3ab to your computer and use it in GitHub Desktop.
A generic class for hosting a SwiftUI.View in a collection view cell.
protocol HasEmptyInitializer {
init()
}
class HostingCollectionViewCell<Content, Model>: UICollectionViewCell where Content: View, Content: HasEmptyInitializer, Model: ObservableObject, Model: HasEmptyInitializer {
private lazy var view: Content = { Content() }()
lazy var model: Model = { Model() }()
lazy var hostingController: some UIViewController = { UIHostingController(rootView: view.environmentObject(model)) }()
override init(frame: CGRect) {
super.init(frame: .zero)
backgroundColor = .clear
hostingController.view.backgroundColor = .clear
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupIfNeeded(in container: UIViewController) {
guard hostingController.parent == nil else { return }
container.addChild(hostingController)
contentView.addSubview(hostingController.view)
hostingController.view.pinEdges()
hostingController.didMove(toParent: container)
}
deinit {
guard hostingController.parent != nil else { return }
hostingController.willMove(toParent: nil)
hostingController.view.removeFromSuperview()
hostingController.removeFromParent()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment