Created
February 22, 2021 21:29
-
-
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.
This file contains hidden or 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
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