Search code examples
iosiphoneswiftuicollectionviewcollectionview

iOS Swift - CollectionView INSIDE UIView XIB INSIDE UIViewController


I can't seem to find any information on how to achieve this, and what I'm trying to achieve is kind of hard to explain, but here it is:

I have a UIViewController that loads a "stack" of reusable UIViews that I've created with a XIB. Within each reusable UIView is a CollectionView, that creates a custom CollectionViewCell for each string in an array.

I have no idea how to accomplish this. No clue whatsoever, and nothing online covers this exact situation. It seems to be one level deeper than any other explanation provides. Every time I try to create the cells for the CollectionView I get a "Must register a nib or a class for the identifier or connect a prototype cell in a storyboard" error.


Solution

  • Figured it out. Yes, if you want to use a CollectionView inside a XIB, and you have a custom CollectionViewCell, you have to create a XIB for the CollectionViewCell. You cannot just have a CollectionViewCell without a XIB in this case. Then, in the ViewController that contains the XIB, you have to use:

    xibView.collectionView.register(UINib(nibName: "CustomCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "CustomCollectionViewCell")
    

    Most tutorials say to do this in viewDidLoad, however I'm creating not just one XIB in the ViewController, but a bunch of them based on data pulled from a database. So I do this within the loop that builds each XIB. I was worried this wouldn't work, but it does.

    The reason why you have to do this continues to elude me.