swiftcollectionviewuicollectionviewflowlayout

collectionView cellForItemAtIndexPath called only one time -swift - programmatically


I have a collectionView that I set with this delegate and datasource:

extension CardView : UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout{


func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
    let numberOfURLS = cardModel?.urlStrings?.count
    return numberOfURLS!
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    
    let videoCell = collectionView.dequeueReusableCell(withReuseIdentifier: "videoCellIdentifier", for: indexPath)
    videoCell.backgroundColor = UIColor.random()
    return videoCell
    
}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return self.bounds.size
}

}

The problem is that the method cellForItemAtIndexpath is called only one time even if the cells returned are more than one.


Solution

  • The collectionView(_:cellForItemAt:) is called only as the cells appear or are about to appear. It won't call it for all of the cells, but only the visible ones (or those about to scroll into view). It is called in a just-in-time manner.

    You can also turn on prefetching (which only works if you turn off “Estimate Size” in the collection view’s “Size inspector” IB or manually set the flow layout’s estimatedItemSize to .zero), but that only makes it a tiny bit more “eager” in terms of fetching cells (fetching those that are going to scroll into view a bit sooner than it would otherwise). It will not fetch all of the cells, but just those that the OS determines might possibly scroll into view soon.