SwiftUI comes with wrong height when using UIHostingController inside UICollectionViewCell

I am trying to display a list of SwiftUI using UICollectionView, what I did is:
  • 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

I notice sometimes, swiftUI only shows half or less half height of cell's height, when I scroll a cell outside screen back to screen, it made me feel the swiftUI is not rendered proper when it's outside screen.

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?
Answered by dibbleme in 652288022
Please ignore this question, I need to re-check my code, it properly somewhere is wrong. I did a mini version app and it works fine.
Accepted Answer
Please ignore this question, I need to re-check my code, it properly somewhere is wrong. I did a mini version app and it works fine.
SwiftUI comes with wrong height when using UIHostingController inside UICollectionViewCell
 
 
Q