Skip to content

Instantly share code, notes, and snippets.

@karigrooms
Created February 23, 2021 19:37
Show Gist options
  • Save karigrooms/90c7295079b628b431fc69d7221799e5 to your computer and use it in GitHub Desktop.
Save karigrooms/90c7295079b628b431fc69d7221799e5 to your computer and use it in GitHub Desktop.
Blog post: SwiftUI with UICollectionView - 7. Refactored to pass data to the SwiftUI Card
import SwiftUI
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
static var reuseIdentifier = "MyCollectionViewCell"
typealias Content = Card.Content
private(set) var host: UIHostingController<Card>?
// MARK: UIHostingController Setup/Cleanup
func embed(in parent: UIViewController, withContent content: Content) {
if let host = self.host {
host.rootView = Card(content: content)
host.view.layoutIfNeeded()
} else {
let host = UIHostingController(rootView: Card(content: content))
parent.addChild(host)
host.didMove(toParent: parent)
// alternative to using constraints
host.view.frame = self.contentView.bounds
self.contentView.addSubview(host.view)
self.host = host
}
}
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