1 創(chuàng)建一個layout
//先創(chuàng)建UICollectionViewFlowLayout的對象
?UICollectionViewFlowLayout?*layout=[[UICollectionViewFlowLayout?alloc]init];
?//同一行相鄰兩個cell的最小間距
? ? layout.minimumInteritemSpacing?=?5;
?//最小兩行之間的間距
? ? layout.minimumLineSpacing?=?5;
在這里還可以設(shè)置大小和上左下右等。。
UICollectionView *view =?[[UICollectionView?alloc]initWithFrame:CGRectMake(0,?0,?375,?667)?collectionViewLayout:layout];
?view.backgroundColor=[UIColor?whiteColor];
?view.delegate=self;
?view.dataSource=self;
?//這個是橫向滑動
?//layout.scrollDirection=UICollectionViewScrollDirectionHorizontal;
? [self.view?addSubview:view];
2 ?必須注冊cell
?//這種是xib建的cell?需要這么注冊
?UINib?*cellNib=[UINib?nibWithNibName:@"CollectionViewCell"?bundle:nil];
? ? [_collectionView?registerNib:cellNib?forCellWithReuseIdentifier:@"CollectionViewCell"];
?//這是頭部與腳部的注冊
?UINib?*cellNib1=[UINib?nibWithNibName:@"CollectionReusableView"?bundle:nil];
? ?[_collectionView?registerNib:cellNib1?forSupplementaryViewOfKind: UICollectionElementKindSectionHeader withReuseIdentifier:@"CollectionReusableView"];
? ? [_collectionView registerNib:cellNib1 forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"CollectionReusableView"];
//cell的點擊事件
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
?//cell被電擊后移動的動畫
? ? [collectionView selectItemAtIndexPath:indexPath animated:YES?scrollPosition:UICollectionViewScrollPositionTop];
}
//頭部試圖的大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
?return?CGSizeMake(50,?60);
}
//頭部和腳部的加載
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
? ? UICollectionReusableView *view=[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"CollectionReusableView"forIndexPath:indexPath];
? ? UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(110,?20,?100,?30)];
?if?([kind isEqualToString:UICollectionElementKindSectionHeader]) {
? ? ? ? label.text=@"頭";
? ? }else{
? ? ? ? label.text=@"腳";
? ? }
? ? [view addSubview:label];
?return?view;
}
//腳部試圖的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section
{
?return?CGSizeMake(50,?60);
}