Can't get UICollectionView to display cells

beev picture beev · Sep 30, 2013 · Viewed 11.5k times · Source

I'm trying to get a UICollectionView to display inside a modally presented view controller. The app is for iPad iOS 7.

I've created subclass of UIViewController (with a nib) and added it like this:

MyViewController *controller = [[MyViewController alloc] init];
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
navController.modalPresentationStyle = UIModalPresentationFullScreen;
navController.navigationBar.barStyle = UIBarStyleBlackTranslucent;

[self presentViewController:navController animated:YES completion:nil];

This view controller is to be the delegate and dataSource for my UICollectionView so I've added UICollectionViewDataSource and UICollectionViewDelegate to the header.

I've put a UICollectionView into the nib and added an outlet to MyViewController:

@property (strong, nonatomic) IBOutlet MyCollectionView *collectionViewController;

I've added this in viewDidLoad in MyViewController:

self.collectionViewController.dataSource = self;
self.collectionViewController.delegate = self;

I've also added the following to MyViewController:

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSLog(@"Items in section: %d", itemsArray.count); // returns correct amount

    return itemsArray.count;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"cellForItemAtIndexPath %@", indexPath); // returns as expected

    static NSString *identifier = @"MyCell";

    [self.collectionViewController registerClass:[MyCollectionCell class] forCellWithReuseIdentifier:identifier];

    MyCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];

    UIImageView *myImageView = (UIImageView *)[cell viewWithTag:100];
    myImageView.image = [UIImage imageNamed:[itemsArray objectAtIndex:indexPath.row]];

    return cell;
}

I've also set up a subclass of UICollectionViewCell with the identifier set to MyCell and added to it a UIImageView with the tag 100.

Whenever I bring up this view controller I'm getting the navigation bar as expected, but the UICollection view I've added to my nib is nowhere to be seen. All I'm seeing is black where the collection view should be. If I change the background colour of MyCollectionView from default to white, I see white where the collection view ought to be. It seems to be bringing up MyCollectionView, but not showing any cells.

Answer

abc123 picture abc123 · Nov 7, 2013

One other point of interest is that if you set the cell's identifier in the nib or storyboard, don't register the nib/class in the collection view controller. Do one or the other, but not both.