「Objective-C」ios開発でUICollectionViewを利用する方法のまとめ

利用方法
#pragma mark — UICollectionViewDataSource

//UICollectionViewCellの個数を表示
– (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 10;
}

//Sectionの個数表示の定義
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 2;
}

//UICollectionViewのコンテンツを表示
– (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
BTCollectionCell *cell =[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];

cell.imageView.image = [UIImage imageNamed:@"tupian"];
cell.titleLabel.text = [NSString stringWithFormat:@"第%d组,第%d个",indexPath.section,indexPath.row];
cell.titleLabel.tag = 100+indexPath.row;

return cell;
}

#pragma mark –UICollectionViewDelegateFlowLayout

//UICollectionView の marginを定義
– (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
//ビュー全体の最上部
UIEdgeInsets top = {5,5,5,5};
return top;
}

//UICollectionViewのサイズを定義
– (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(140, 80);
}

#pragma mark –UICollectionViewDelegate

//UICollectionViewを選択した時呼び出すメソッド
– (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
BTCollectionCell *cell = (BTCollectionCell *)[collectionView cellForItemAtIndexPath:indexPath];

UILabel *label = (UILabel *)[cell viewWithTag:100+indexPath.row];
label.backgroundColor = RGBACOLOR(42, 183, 251, 1);
label.textColor = [UIColor whiteColor];

Mac OS X

Posted by arkgame