import "ViewController.h"
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
{
UICollectionView *collection; //網(wǎng)格視圖
}
@end
//設(shè)置可重用標(biāo)識符
static NSString * const reuseID = @"cell";
@implementation ViewController
-
(void)viewDidLoad {
[super viewDidLoad];//創(chuàng)建一個布局對象
UICollectionViewFlowLayout *flowlayout = [[UICollectionViewFlowLayout alloc]init];//設(shè)置每個格子的大小
flowlayout.itemSize = CGSizeMake(100, 100);//設(shè)置每個格子的最小水平間距
flowlayout.minimumInteritemSpacing = 20;//設(shè)置行間距 最小行間距
flowlayout.minimumLineSpacing = 20;//設(shè)置組與組之間的間隔
flowlayout.sectionInset = UIEdgeInsetsMake(50, 10, 0, 10);
//創(chuàng)建網(wǎng)格對象
collection = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:flowlayout];//設(shè)置代理
collection.delegate = self;
collection.dataSource = self;//設(shè)置網(wǎng)格背景顏色
collection.backgroundColor = [UIColor greenColor];//注冊cell
[collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseID];//將網(wǎng)格添加到父視圖上
[self.view addSubview:collection];
}
//=========數(shù)據(jù)源方法=========
//設(shè)置組數(shù)
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 5;
}
//設(shè)置行數(shù)
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 5;
}
//設(shè)置 cell 內(nèi)容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
//根據(jù)可重用標(biāo)識符查找cell
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseID forIndexPath:indexPath];
//設(shè)置cell的背景顏色
cell.backgroundColor = [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0)green:((float)arc4random_uniform(256) / 255.0)blue:((float)arc4random_uniform(256) / 255.0)alpha:1.0];
return cell;
}