Search code examples
iosxcodeuicollectionviewuistoryboard

How to call the correct datasource within the UICollectionViewDataSource and UICollectionViewDelegateFlowLayout methods?


Within a UITableViewController, with static UITableViewCells, I am trying to create a reusable grid with a definite number of cells per row, variable widths and heights.

enter image description here

In Identifying and fixing auto layout issue from log output, it was suggested that UICollectionViews would be a better approach.

Using static UICollectionViewCells, as per https://robkerr.com/how-to-create-a-static-uicollectionview/, I have been able to set up one collection view grid.

BUT, I'm having difficulty adding a second, separate, and different grid in another UITableViewCell.

I thought I might be able to create separate IB outlets for the UICollectionView and then use this to select which data to use.

@IBOutlet weak var myCollectionView: UICollectionView!

@IBOutlet weak var endingsCV: UICollectionView!

extension NounsTVC: UICollectionViewDataSource
{
func collectionView( _ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
    if self == myCollectionView
    {
        print("myCollectionView", cellIds.count)
        return cellIds.count}
    else if self == endingsCV
    {
        print("endingsCV", cellIds2.count)
        return cellIds2.count
    }
}

This crashes without finding the Collection View reuse identifiers.

I've tried using the UICollectionView Identity Restoration ID, but I might not have the correct syntax or placement.

How do I call the correct datasource to configure the cells within the UICollectionViewDataSource and UICollectionViewDelegateFlowLayout methods?


Solution

  • I'm not sure if this is the best way to do this, but it works if I use the instantiated name of the collection view instead of 'self'.

    @IBOutlet weak var myCollectionView: UICollectionView!
    
    @IBOutlet weak var endingsCV: UICollectionView!
    
    extension NounsTVC: UICollectionViewDataSource
    {
    func collectionView( _ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
    if myCollectionView == myCollectionView
    {
        print("myCollectionView", cellIds.count)
        return cellIds.count}
    else if endingsCV == endingsCV
    {
        print("endingsCV", cellIds2.count)
        return cellIds2.count
    } }