Skip to content

Instantly share code, notes, and snippets.

@karigrooms
Created February 23, 2021 20:09
Show Gist options
  • Save karigrooms/73c944562dce8385592bfc85302cdc80 to your computer and use it in GitHub Desktop.
Save karigrooms/73c944562dce8385592bfc85302cdc80 to your computer and use it in GitHub Desktop.
Blog post: SwiftUI with UICollectionView - 9. Subclass for embedding a SwiftUI View inside of UICollectionViewCell
import SwiftUI
import UIKit
/// Subclass for embedding a SwiftUI View inside of UICollectionViewCell
/// Usage: `class MySwiftUICell: SwiftUICollectionViewCell<Card> { ... }`
open class SwiftUICollectionViewCell<Content>: UICollectionViewCell where Content: View {
/// Controller to host the SwiftUI View
private(set) var host: UIHostingController<Content>?
/// Add host controller to the heirarchy
func embed(in parent: UIViewController, withView content: Content) {
if let host = self.host {
host.rootView = content
host.view.layoutIfNeeded()
} else {
let host = UIHostingController(rootView: content)
parent.addChild(host)
host.didMove(toParent: parent)
self.contentView.addSubview(host.view)
self.host = host
}
}
// MARK: Controller + view clean up
deinit {
host?.willMove(toParent: nil)
host?.view.removeFromSuperview()
host?.removeFromParent()
host = nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment