Collection view cellForItemAt indexPath not getting called (Swift)

ios, swift, uicollectionview

Solution

If you are pretty sure that the `dataSource` of the collectionView is connected to the viewController (it should be by default), then you should `reloadData()` because the collectionView reading from `dataSourceItems`. To understand the case, add a break point in `cellForItemAt` and add another one in `viewDidAppear` and check which one is called first?

override func viewDidAppear(_ animated: Bool) {

    switch self.presentingViewController!.title! {
    case "CounterBuildVC":
        dataSourceItems = counterBuildItems
    case "FreeBuildVC":
        dataSourceItems = freeBuildItems
    case "CaptureKrakenVC":
        dataSourceItems = captureKrakenItems
    default:
        break
    }

    collectionView.reloadData()
}

Hope that helped.

Problem

I created a collection view controller from story board, and set its custom class to `ItemCollectionVC`, the custom class of its cell to `ItemCell`, and set its reuse identifier to `Cell` Here's my `ItemCollectionVC` class: ``` import UIKit private let reuseIdentifier = "Cell" class ItemCollectionVC: UICollectionViewController { var dataSourceItems: [Items] = [] var counterBuildItems: [Items] { let weaponItemArray = WeaponItems.weaponItems as [Items] let defenseItemArray = DefenseItems.defenseItems as [Items] return weaponItemArray + defenseItemArray } var freeBuildItems = WeaponItems.weaponItems as [Items] var captureKrakenItems: [Items] { let weaponItemArray = WeaponItems.weaponItems as [Items] let abilityItemArray = AbilityItems.abilityItems as [Items] return weaponItemArray + abilityItemArray } override func viewDidAppear(_ animated: Bool) { switch self.presentingViewController!.title! { case "CounterBuildVC": dataSourceItems = counterBuildItems case "FreeBuildVC": dataSourceItems = freeBuildItems case "CaptureKrakenVC": dataSourceItems = captureKrakenItems default: break } } override func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return dataSourceItems.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ItemCell cell.cellImage.image = dataSourceItems[indexPath.row].image print(dataSourceItems.count) return cell } } ``` When the collection view controller is presented, it's empty, what could cause the problem?

Original source

Related problems