123

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 (myCollectionView) that uses custom UICollectionViewCell's that I have subclassed. The subclassed cells (FullReceiptCell) contain UITableView's and are the size of the viewcontroller. I am trying to allow for horizontal scrolling between the FullReceiptCells.

The subclassed UICollectionViewController that contains myCollectionView is being pushed on to a nav controller stack. Currently, myCollectionView loas and horizontal scrolling is enabled. However, no cells are visible. I have confirmed that

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

has run and is returning an integer greater than 0. I have also confirmed that myCollectionView's delegate and datasource are properly set in IB to the subclassed UICollectionViewController.

The method where the cells are to be loaded:

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

is not being called.

Here is where I push the UICollectionViewController and my viewDidLoad method within that controller (NOTE: initWithBill is an override of the normal initializer):

In the prior ViewControllers .m file:

FullReceiptViewController *test = [[FullReceiptViewController alloc] initWithBill:currentBill];
test.title = @"Review";
[self.navigationController pushViewController:test animated:YES];

In FullReceiptViewController.m:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.myCollectionView registerClass:[FullReceiptCell class] forCellWithReuseIdentifier:@"FullReceiptCellIdentifier"];
    self.myCollectionView.pagingEnabled = YES;
    // Setup flowlayout

    self.myCollectionViewFlowLayout = [[UICollectionViewFlowLayout alloc] init];
    [self.myCollectionViewFlowLayout setItemSize:CGSizeMake(320, 548)];
    [self.myCollectionViewFlowLayout setSectionInset:UIEdgeInsetsMake(0, 0, 0, 0)];
    [self.myCollectionViewFlowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    self.myCollectionViewFlowLayout.minimumLineSpacing = 0;
    self.myCollectionViewFlowLayout.minimumInteritemSpacing = 0;
    [self.myCollectionView setCollectionViewLayout:myCollectionViewFlowLayout];
    //testing to see if the collection view is loading
    self.myCollectionView.backgroundColor = [UIColor colorWithWhite:0.25f alpha:1.0f];

Any clue as to why it is not being called?

1
  • I am using XIB. I can't dequeue anything in cellForItemsAtIndexPath because it never gets called. Feb 3, 2013 at 8:20

35 Answers 35

150

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.

11
  • Can you elaborate a bit more. Same is happening for me Oct 15, 2013 at 17:32
  • I just discovered that you need to be careful with collectionViewContentSize, too Feb 1, 2014 at 15:14
  • 55
    In case you are using autolayout - be sure to set a height constraint on the collectionView - wasted many hours on this!
    – bpn
    Feb 21, 2014 at 17:44
  • for the record height constrain didn't work for me.. horizontal center constrains did the trick Nov 2, 2014 at 19:09
  • 4
    If your collectionView is constrained to topLayoutGuide with AutoLayout, and is not supposed to scroll under NavigationBar, make sure to uncheck Adjust Scroll View Insets on your ViewController on Storyboard. Apr 15, 2016 at 14:19
116

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

4
  • This was my issue as well! It's a little counterintuitive, so it didn't even occur to me. Thanks for this!
    – WendiKidd
    Feb 12, 2016 at 17:43
  • Same for me! its so easy to overlook that! thanks again
    – arvidurs
    Sep 6, 2016 at 21:53
  • Facepalm here, thank you for pointing this out (4 years ago).
    – Milander
    Aug 8, 2018 at 15:18
  • I was facing the same issue. Thanks Dec 24, 2018 at 15:39
37

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.

4
  • 2
    For example to use the full available size, return collectionView.frame.size from collectionViewContentSize (not simply collectionView.contentSize which defaults to 0, 0) Apr 14, 2015 at 17:44
  • 1
    Thanks! This answer helped me b/c I have a custom UICollectionViewLayout. If I started up the app in simulator in landscape orientation, some cells were not appearing in the initial view. Overriding the content size fixed this problem for me. Apr 12, 2017 at 5:24
  • 2
    Thank you. In my case the collectionViewContentSize incorrectly returned 0 for the width, that's why the cellForItemAtIndexPath was not getting called.
    – izerik
    Mar 22, 2018 at 13:52
  • Thanks for this answer -- in my case, func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize was returning a 0 length for one of the parameters (size, width) -- therefore, cellForItemAt method would not be called after reloadData() is called, in this case.
    – markckim
    Dec 14, 2022 at 8:00
18

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

self.automaticallyAdjustsScrollViewInsets = NO;
1
  • 1
    I spent so much time on this - and it all came down to that. If using storyboard or XIB, look at the parent view controller and deselect "Adjust Scroll View Insets" in the Attribute Inspector which is turned on by default. I tried all the other answers and they didn't work, it came down to this.
    – etayluz
    Mar 29, 2016 at 21:03
16

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.

4
  • 1
    I didn't show it but I already have the delegate and datasource noted in the header file. Additionally, I have wired the IBOutlet to myCollectionView. The delegate and datasource for this collectionview have been set to FullReceiptViewController. The strange thing is that numberOfItemsInSection (a datasource protocol method) is getting called and returning an integer greater than 0. Feb 3, 2013 at 8:31
  • Hmm, When you launch the application does the Collection view show or do anything? It sounds like it does have some items in it if numberOfItemsInSection returns something greater than 0. Feb 4, 2013 at 0:46
  • Thanks for following up. The collectionview does show... I can tell because I changed the background color. I believe I have found the problem: [self.myCollectionViewFlowLayout setItemSize:CGSizeMake(320, 548)]; This was too big. If I decrease the height to 410, I can get the cellForItemAtIndexPath method to be called. Feb 4, 2013 at 7:13
  • @AnthonyCastelli Hello,I am also facing the same issue, numberOfItemsInSection being called on pop to viewController but not cellForItemsAtIndexPath. so do you get the clue? Nov 24, 2013 at 8:01
15

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)
1
  • This is the answer solved my problem! The override method func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { <#code#> } does not work for me.
    – Mike
    Feb 23, 2019 at 19:15
11

I was using autolayout, and in my case height constraint was missing

6

In my case, what I had very stupidly forgotten to do was implement the UICollectionViewDataSource protocol method numberOfItemsInSection, so that is another thing to check.

6

My issue was that I had 2 collection views within the same view, and both were sharing a computed UICollectionViewFlowLayout instance. Once I created separate instances of the same flow layout, it worked fine.

6

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.

Set estimate size to Custom

0
6

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.

0
5

Ten minutes ago I also encountered this problem, I made a silly mistake.

My intention is to use UICollectionViewFlowLayout,

But because of mistakes, I used UICollectionViewLayout.

0
5

I forgot to set the autoresizing mask to false on the collection view:

collectionView.translatesAutoresizingMaskIntoConstraints = false
5

Also, make sure that reloadData is not called while collection view is updating with animation (insert, delete, update or performBatchUpdates).

0
5

In my case, set collectionView.prefetchingEnabled = NO; solved my problem. Only works on iOS 10.

2
  • 2
    I upvoted that answer some time ago and today it helped me again :D You deserve a Noble for this answer man. Thanks again! Apr 23, 2020 at 9:36
  • this answer worked for me! I wish there was an explanation as to why included with it because I never had it set to true to begin with. Jun 7, 2020 at 22:48
3

It was happening for me when item height == 0 by fixing that cellForItem method was called.

3

In my case, changing UINavigationBar's translucent to NO solved the problem.

0
3

In Xcode 7.0.1, we got this problem when we copied a storyboard and accompanying code from another project. The collection view had a custom flow layout set in the storyboard. Solution was to:

  • Remove the flow layout in IB
  • Compile/run the app
  • Set the flow layout back

Now it worked :)

3

In storyboard/xib UICollectionView property cellSize MUST not be {0, 0}

3

If you're using collection view protocols you must connect the CollectionViewDataSource and CollectionViewDelegate protocols to your ViewController. Interface builder outlets

0
2

Make sure numberOfSectionsInCollectionView returns a positive integer as well.

There has to be at least one section in the collection.

2

Make sure -(NSInteger) collectionView:numberOfItemsInSection: is returning a positive (read, greater than zero) value. It may be a matter of placing [self.collectionView reloadData]; in the completion handler.

0
2

For me, I update the height of self.view (the collectionView's superview) via autolayout, and MUST call layoutIfNeeded after that.

[self.view mas_updateConstraints:^(MASConstraintMaker *make) {
    make.height.equalTo(@(height));
}];
[self.view layoutIfNeeded];
2

When using UICollectionViewDelegateFlowLayout be careful on what this function returns. Both width and height should be greater than 0. I used window as frame reference but due to complicated view hierarchy window was nil at runtime. If you need adjust the width of the element based on screen width use UIScreen.main.bounds.

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

It can be realated layout problems. Check layout warnings from console, if exist.

2

In my case the collection view was not fully visible in its parent view due to wrong auto layout constraints. So fixing the constraints made the collection view all visible and cellForItemAtIndexPath was called.

1

Same happened to me. I had 2 UICollectionViews and I removed once since I didn't need that. After that I realised that the CellForItemAtIndexPath was not getting called but the other required methods. I tried all of the above but then I did the standard magic. Removed the collection view from storyboard and added again. Then it started working. Not sure why and I have no explanation but maybe some connection issues.

1
  • I copied my UICollectionView from another UIViewController in storyboard. I deleted the the CollectionView and added again to make it work. Thank you for your answer. Jan 24, 2017 at 14:00
1

Just resolved this issue, for a somewhat specific situation.

In my case, I was manually initializing the UICollectionViewController in a parent ViewController, and then adding the UICollectionViewController's view as a subview.

I resolved the issue by calling 'setNeedsLayout' and/or 'setNeedsDisplay' on the collectionView in the parent's viewDidAppear:

- (void)viewDidAppear:(BOOL)animated {
   [super viewDidAppear:animated];
   [_collection.view setNeedsLayout];
   [_collection.view setNeedsDisplay];
}
0
1

reloadSections instead of reloadData did it for me.

I don't know why reloadData did not work.

1
  • Weird... same here. Configuring the collection view programmatically. collectionView.reloadData() didn't work but collectionView.reloadSections(IndexSet(integer:0)) causes cellForItemAt for each row to be called.
    – clearlight
    Dec 14, 2022 at 6:07
0

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.