#import "ViewController.h"
#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@end
@implementation ViewController
//全局變量
static NSString *cell_identy = @"cell";
- (void)viewDidLoad {
[super viewDidLoad];
/*____________ UICollectionView 集合視圖 ___________________________________________________*/
/**
* 步驟:
1.布局類
2.集合視圖
3.注冊(cè)單元格
4.定制單元格
*/
//1??布局類
/**
* 設(shè)置單元格:大小 間距 頭視圖大小 尾視圖大小 滑動(dòng)方向
*/
//I.創(chuàng)建布局對(duì)象
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
//II.設(shè)置布局屬性
//1.單元格大小 --> 決定 行/列 的單元格的個(gè)數(shù)
layout.itemSize = CGSizeMake((kScreenW-40)/3.0, kScreenW/3.0);
//2.設(shè)置最小間隙
/**
* 滑動(dòng)方向垂直:水平間隙由單元格寬度和集合視圖寬度決定 最小不能低于最小間隙
垂直間隙就是最小垂直間隙
水平方向滑動(dòng):垂直間隙由單元格高度和集合視圖高度決定 最小不能低于最小間隙
水平間隙就是最小水平間隙
*/
//垂直方向間隙 (間隙本身是水平的)
layout.minimumLineSpacing = 20;
//水平方向間隙 (間隙本身是垂直的)
layout.minimumInteritemSpacing = 1;
//3.設(shè)置滾動(dòng)方向(向哪滑動(dòng))
/**
* UICollectionViewScrollDirectionVertical,垂直
UICollectionViewScrollDirectionHorizontal 水平
*/
layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//4.頭/尾視圖尺寸
// layout.headerReferenceSize = CGSizeMake(0, 0);
// layout.footerReferenceSize = CGSizeMake(0, 0);
//2??集合視圖
//I.同步布局類對(duì)象創(chuàng)建
UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout];
//II.屬性
collectionView.delegate = self;
collectionView.dataSource = self;
[self.view addSubview:collectionView];
//3??注冊(cè)單元格
/**
* 將UICollectionViewCell類的單元格 加上 cell_identy復(fù)用標(biāo)記
*/
[collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:cell_identy];
}
#pragma mark --UICollectionViewDataSource
//返回item個(gè)數(shù)
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return 30;
}
//返回單元格 復(fù)用
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
//?使用注冊(cè)單元格
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cell_identy forIndexPath:indexPath];
cell.backgroundColor = [UIColor cyanColor];
return cell;
}
#pragma mark --UICollectionViewDelegateFlowLayout
//邊緣大小
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
return UIEdgeInsetsMake(10, 10, 10, 10);
}
@end
屏幕快照 2016-03-05 上午11.12.44.png