Created
February 23, 2021 19:37
-
-
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
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
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