Pratibha Shetty
Pratibha Shetty

Reputation: 21

Collectionview cell for row at index path not getting called for subsequent sections if the current section cell height is zero

I came across an issue in collection view in our project -

  1. Collectionview consist of 4 sections. Each section consist of 1 cell.

  2. If we keep height zero for a collection view cell in section 0, cellforrrowatindexpath will not be called for section zero. The problem we are facing is cellforrowatindexapath will not be called for subsequent sections as well. Collection view will not display anything on the screen though other section cells heights are provided.

Updated:

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

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


 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
      Switch indexpath.section {
     case 0: return  CGSize(width: UIScreen.main.bounds.width, height: 0)
         case 1:  return CGSize(width: UIScreen.main.bounds.width, height: 200)
         case 2: return CGSize(width: UIScreen.main.bounds.width, height: 300)
      }
 }

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
 Switch indexpath.section {
     case 0: return A()
         case 1: return B()
         case 2: return C()
      }
}

If anyone has better understanding of why collection view works in this way please let me know.

Upvotes: 0

Views: 1247

Answers (3)

kseniiap
kseniiap

Reputation: 463

If you use storyboard, try to change Collection View's Estimate Size to None in Size Inspector section.

Please check:

screenshot

Upvotes: 2

DonMag
DonMag

Reputation: 77647

Add this in viewDidLoad():

    if let fl = theCollectionView.collectionViewLayout as? UICollectionViewFlowLayout {
        fl.estimatedItemSize = CGSize(width: 1, height: 1)
    }

Now sizeForItemAt and cellForItemAt will be called for your additional sections.

Upvotes: 0

Arik Segal
Arik Segal

Reputation: 3031

I had a similar issue once. It might be resolved by returning CGFloat.leastNonzeroMagnitude or 0.1, instead of 0.

Upvotes: 0

Related Questions