Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UICollectionView's cellForItemAtIndexPath is not being called

For those who stumble here later.... the reason:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

was not being called was because of the itemSize for the collectionViewFlowLayout's height was too big.

[self.myCollectionViewFlowLayout setItemSize:CGSizeMake(320, 548)];

If I change the height to 410, it will execute cellForItemAtIndexPath.


In my case, it was because my layout class incorrectly subclassed from UICollectionViewLayout instead of UICollectionViewFlowLayout


The cellForItemAtIndexPath will not get called if you do not provide the content size information to collection view.

  1. If you are using Flow layout: You need to set the item sizes properly.
  2. If you have a custom layout subclassed from UICollectionViewLayout: Ensure you are returning a proper size from the collectionViewContentSize method.

In case of the latter, you will also observe that your layoutAttributesForElementsRect is also not called. The reason is that you have not specified what is your content size and by default the size will be CGSizeZero. This basically tell collection view that you don't have any content to paint so it does not bother asking you for attributes or cells.

So, just override collectionViewContentSize and provide a proper size there, it should solve your problem.


For a more complicated view hierachy please check this blog. It saved my life!

self.automaticallyAdjustsScrollViewInsets = NO;

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.


If your class is subclass from UICollectionviewController and you are creating collectionView programmatically then use

let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .Vertical
    layout.itemSize = CGSizeMake(50, 50)

    collectionView?.setCollectionViewLayout(layout, animated: false)