I am trying to display a list of SwiftUI using UICollectionView, what I did is:
code to host the UIHostingController:
code to pass SwiftUIView to cell, called when cellForItemAt:indexPath::
code to add widgetHostingVC to parentVC, called when cell willDisplay:
code to remove widgetHostingVC from parentVC, call when cell didEndDisplaying:
Anyone know what is the problem cause the swiftUI not render with correct height?
using UICollectionViewCell to host the UIHostingController
when the cell willDisplay, I added the UIHostingController to parent view controller
remove it from parent controller when cell didEndDisplay
code to host the UIHostingController:
Code Block class MyCell: UICollectionViewCell { private lazy var widgetHostingVC: UIHostingController<AnyView> = { let vc = UIHostingController(rootView: AnyView(Text(""))) return vc }() /* BTW, widgetHostingVC's view is added to contentView during init, with constraints edge to edge */ }
code to pass SwiftUIView to cell, called when cellForItemAt:indexPath::
Code Block func config(_ swiftUIView: AnyView) { self.widgetHostingVC.rootView = swiftUIView }
code to add widgetHostingVC to parentVC, called when cell willDisplay:
Code Block func addViewControllerToParentVC(_ parentVC: UIViewController) { parentVC.addChild(self.widgetHostingVC) self.widgetHostingVC.didMove(toParent: parentVC) self.contentView.addSubview(self.widgetHostingVC.view) // setup constraints }
code to remove widgetHostingVC from parentVC, call when cell didEndDisplaying:
Code Block func removeViewControllerFromParentVC() { self.widgetHostingVC.removeFromParent() }
Anyone know what is the problem cause the swiftUI not render with correct height?