0

I would like to embed a ViewController inside a UICollectionView cell, I tried to search on the internet but I haven't found anything applicable to my case.

I've done this so far,

this is the View Controller:

class ExploreViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    view.backgroundColor = .systemGreen
}
}

This is the collectionViewCell:

class ExploreCollectionViewCell: UICollectionViewCell {

let exploreViewController = ExploreViewController()

override init(frame: CGRect) {
    super.init(frame: frame)

    addSubview(exploreViewController.view)
}

required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

}

Basically I'm instantiating a ViewController inside the cell and displaying its view;

I don't think this is actually the best thing to do but honestly I don't know how to implement it in a different way.

The best thing would be to actually embed the viewController inside the cell, do you know how could I do it?

  • 1
    What's the issue you are facing? – Frankenstein May 30 '20 at 22:34
  • I don't know if just displaying the view would compromise the efficiency of the ViewController –  May 30 '20 at 22:36
  • Have you used the search and checked out among others [the post with an almost identical title](https://stackoverflow.com/questions/42498129/adding-a-uiviewcontroller-inside-a-uicollectionview-cell)? Which also leads to Apple's [container view controller guide](https://developer.apple.com/library/archive/featuredarticles/ViewControllerPGforiPhoneOS/ImplementingaContainerViewController.html). Google also seems to find a number of possible implementations with, e.g., "view controllers in cells". – Roope May 30 '20 at 22:56
  • I think what you're looking for a is a Container View. It's basically a UIView that can connect to it's own ViewController. – nicksarno May 31 '20 at 05:21
  • Thanks Guys, your comments have been helpful –  May 31 '20 at 08:32

0 Answers0