Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collection view cellForItemAt indexPath not getting called (Swift)

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?

like image 605
Bright Avatar asked Dec 03 '22 23:12

Bright


1 Answers

One of three things caused this problem, pretty much every time I have encountered it, in a TableView or CollectionView:

1) Your ViewController is not the dataSource of your UICollectionView

2) numberOfRows or numberOfSections method returns 0

3) The height of your cell is 0, either due to constraint problems, or a heightForCell method being not/improperly implemented.

It's impossible to say which of these is your problem, and it's always possible that you've encountered something strange. Make certain that none of these is your problems, before exploring less likely options.

like image 155
dylanthelion Avatar answered May 08 '23 00:05

dylanthelion