このような何かがそれを行う必要があります。微調整などが必要になる場合があります。いくつかの変更が必要なセクションを使用していないと仮定すると..
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@end
#import "ViewController.h"
#define WIDTH 200
#define HEIGHT 200
#define XMARGIN 50
#define YMARGIN 20
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (assign, nonatomic) int numberOfCols;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
UINib* cellNib = [UINib nibWithNibName:@"CollectionCell" bundle:nil];
[self.collectionView registerNib:cellNib forCellWithReuseIdentifier:@"CollectionCell"];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 6;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"CollectionCell" forIndexPath:indexPath];
NSLog(@"Row number %d",indexPath.row);
int rem = (indexPath.row / self.numberOfCols);
NSLog(@"col number %d", rem);
if ( rem % 2 == 0 )
cell.backgroundColor = [UIColor yellowColor];
else
cell.backgroundColor = [UIColor greenColor];
return cell;
}
#pragma mark – UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
self.numberOfCols = (collectionView.frame.size.width - (XMARGIN*2)) / (WIDTH);
NSLog(@"Number of cols is %d",self.numberOfCols);
return CGSizeMake(WIDTH,HEIGHT);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
return UIEdgeInsetsMake(XMARGIN, YMARGIN, XMARGIN, YMARGIN);
}
- (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[self.collectionView reloadData];
}