Only my second time using UICollectionView\'s and perhaps I have bitten off more than I can chew but nevertheless:
I am implementing a UICollectionView (myCollection
In storyboard/xib UICollectionView property cellSize MUST not be {0, 0}
I was having a similar problem. But instead cellForItemAtIndexPath
was called when the number of items was > 1, but not when there was only a single item. I tried many of the proposed solutions here and similar to many I found that it had to do with item sizing. For me the solution was to change the estimate size of the UICollectionView
from Automatic to Custom.
Make sure numberOfSectionsInCollectionView
returns a positive integer as well.
There has to be at least one section in the collection.
In my case I had the collectionView
in a UIStackView
with alignment = .center
. So the collectionView
did not have a width. When setting the stackView.alignment
to .fill
everything was fine.
Maybe I'm just overlooking it, but it appears your missing your delegate and data source. In your header file, make sure you have added these:
<UICollectionViewDelegate, UICollectionViewDataSource>
and in your viewDidLoad method add this:
self.myCollectionView.delegate = self;
self.myCollectionView.dataSource = self;
Also, if you are loading it via an .xib, make sure you are have connected the IBOutlet to the UICollectionView.
In my case I had to adjust the estimated Content size. content size did not do it.
let layout = collectionVC.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.itemSize = CGSize(width: 100, height: 100)
layout.estimatedItemSize = CGSize(width: 100, height: 100)