UICollectionViewの使い方

1.IBからCellサイズなどを設定する.Outletを接続しておく.

2.UIViewControllerのViewDidLoadメソッドでデリゲートとデータソースを設定しておく.registerClassはセルを登録している. viewDidLoadしているのがUICollectionViewControllerのサブクラスの場合,registerClassをしてはいけない.

- (void)viewDidLoad
{
  [superviewDidLoad];
// Do any additional setup after loading the view.
  self.collectionView.delegate = self;
  self.collectionView.dataSource = self;
  [self.collectionViewregisterClass:[UICollectionViewCellclass] forCellWithReuseIdentifier:@"MY_CELL"];
}

3.デリゲートメソッドを実装する.必須なメソッドはアイテム数の指定とセルの生成.

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

セルの生成は

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
  UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MY_CELL"forIndexPath:indexPath];
  cell.backgroundColor = [UIColorwhiteColor];
  return cell;
}

UICollectionViewCellはカスタムしたセルでもOK.カスタムしたセルを使う場合はregisterClassも変更する.ReuseIdentifierはregisterClassと揃える.