// 初始化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]forCellWithReuseIdentifier:@"cell"];
//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];
//自定義
VideoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identify forIndexPath:indexPath];
[cell sizeToFit];
if (!cell) {
}
VideoModel *model = [self.videoModelsobjectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:model.videoImgURL];
[cell.imgView setImageWithURL:url];
cell.titleLbale.text = model.videoTitle;
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);
}