0

trying to use UICollectionView as follows

the .h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UICollectionViewDataSource, UICollectionViewDelegate>

@property(strong, nonatomic) UICollectionView *collectionView;
@end

and the .m

#import "ViewController.h"

@interface ViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>

@end

@implementation ViewController
@synthesize collectionView;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    UICollectionViewLayout *layout = [[UICollectionViewLayout alloc] init];
    collectionView=[[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:layout];
    [collectionView setDataSource:self];
    [collectionView setDelegate:self];
    [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
    [collectionView setBackgroundColor:[UIColor greenColor]];
    [self.view addSubview:collectionView];
}



-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return 15;
}

-(UICollectionViewCell *) collectionView:(UICollectionView *)mycollectionView cellForItemAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    UICollectionViewCell *cell=[mycollectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    cell.backgroundColor=[UIColor redColor];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(50, 50);
}
@end

I was intended to show a list of green rect on a red background, but only the red background shows, what was I missing?

armnotstrong
  • 7,047
  • 10
  • 51
  • 108

1 Answers1

2

Use "UICollectionViewFlowLayout" in place of "UICollectionViewLayout" while initializing Layout.

UICollectionViewLayout *layout = [[UICollectionViewFlowLayout alloc] init];

link

aparna
  • 36
  • 3