-1

I am unable to display the second cell despite registering it to the collectionView. Does anyone know why this is the case? The cell exists as when I switch the row the other cell displays instead.

class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {


    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = UIColor.white


        collectionView?.register(HeaderCell.self, forCellWithReuseIdentifier: "HeaderCell")
        collectionView?.register(SummaryCell.self, forCellWithReuseIdentifier: "SummaryCell")


    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        }
        return 1
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        if (indexPath.row == 0) {

            let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: "HeaderCell", for: indexPath) as! HeaderCell

            return cell1

        } else {
            let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: "SummaryCell", for: indexPath) as! SummaryCell

            return cell2
        }

    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        return CGSize(width: view.frame.width, height: 200)

    }

}

I have looked a this but still unable to get it to work.

P.S. I am programming everything programmatically.

Chace
  • 561
  • 10
  • 28

2 Answers2

4

You have registered 2 cells but you are returning only 1 row.Try returning 2 items.

//numberOfItemsInSection
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
        return 2
    }
Tushar Sharma
  • 2,839
  • 1
  • 16
  • 38
0

None of the answer correctly/completely solves the issue. However I did use some of the suggestions to get it to work properly by adding the following:

override func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 2
}

And changing indexPath.row to indexPath.section

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    if (indexPath.section == 0) {

        let cell1 = collectionView.dequeueReusableCell(withReuseIdentifier: "HeaderCell", for: indexPath) as! HeaderCell

        return cell1

    } else {
        let cell2 = collectionView.dequeueReusableCell(withReuseIdentifier: "SummaryCell", for: indexPath) as! SummaryCell

        return cell2
    }
}
Chace
  • 561
  • 10
  • 28