// 初始化layout
UICollectionViewFlowLayout *fowLayout = [[UICollectionViewFlowLayout alloc] init];
//设定全局的行间距,如果想要设定指定区内Cell的最小行距,可以使用下面方法:
fowLayout.minimumLineSpacing = 10;
//设定全局的Cell间距,如果想要设定指定区内Cell的最小间距,可以使用下面方法:
fowLayout.minimumInteritemSpacing = 10;
//itme上左下右的间距
fowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
//设定滚动方向,有UICollectionViewScrollDirectionVertical和UICollectionViewScrollDirectionHorizontal两个值。
fowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
//设置item大小
fowLayout.itemSize = CGSizeMake(80.0 , 80.0);
UICollectionView * collectionView = [[UICollectionViewalloc] initWithFrame:CGRectMake(0,0, 320, 100)collectionViewLayout:flowLayout];
//注册单元格
//1、正常方式
[collectionView registerClass:[UICollectionViewCell class]forCellWithReuseIdentifier:identifier];
//2、自定义方式
[collectionView registerClass:[VideoCell class]forCellWithReuseIdentifi
//3、xib自定义方式
[collectionViewregisterNib:[MyCellnib]forCellWithReuseIdentifier:@"MyCell"];
collectionView.backgroundColor = [UIColor whiteColor];
collectionView.delegate =self;
collectionView.dataSource =self;
[self.viewaddSubview:collectionView];
--------------委托代理【与tableview类似】--------------
#pragma mark - collectionView delegate
//设置分区
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
//每个分区上得元素个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 24;
}
//设置元素内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identify = @"cell";
UICollectionViewCell * cell =[collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
[cell sizeToFit];
cell.backgroundColor =[UIColor greenColor];
//自定义
return cell;
}
//设置元素的的大小框【如果上面fowLayout已经设置可以不实现以下方法】
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
UIEdgeInsets top = {30,15,30,15};
return top;
}
//设置元素大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(140,160);
}