Created
February 23, 2021 20:09
-
-
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
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 | |
/// 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