#import <UIKit/UIKit.h> @interface myHeadView : UICollectionReusableView { UILabel *TitleLable; } -(void)setTextTitle; @end
#import "myHeadView.h" @implementation myHeadView -(instancetype)initWithFrame:(CGRect)frame{ if (self =[super initWithFrame:frame]) { [self createUI]; } return self; } -(void)createUI{ TitleLable= [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 100, 100)]; [self addSubview:TitleLable]; } //这是头部 -(void)setTextTitle { TitleLable.text=@"哈哈"; } @end
#import "ViewController.h" #import "myHeadView.h" #import "myHeadView.h" @interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout> { UICollectionView *_myConllectionView; NSMutableArray *_dataArray; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; _dataArray =[[NSMutableArray alloc]initWithObjects:[UIColor redColor],[UIColor greenColor],[UIColor blueColor],[UIColor grayColor],[UIColor lightGrayColor],[UIColor purpleColor], nil]; UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc]init]; [layout setHeaderReferenceSize:CGSizeMake(320, 50)]; //设置headview 的大小 layout.minimumInteritemSpacing=10; //cell之间左右的 layout.minimumLineSpacing=10; //cell上下间隔 layout.itemSize=CGSizeMake(80,140); //cell的大小 layout.sectionInset=UIEdgeInsetsMake(5, 9, 5, 9); layout.headerReferenceSize = CGSizeMake(320, 50); _myConllectionView =[[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:layout]; [_myConllectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"]; [_myConllectionView registerClass:[myHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeadView"]; _myConllectionView.delegate=self; _myConllectionView.dataSource=self; [self.view addSubview:_myConllectionView]; } -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { return 2; } -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return _dataArray.count; } -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath]; cell.backgroundColor=[_dataArray objectAtIndex:indexPath.row]; return cell; } -(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath { UICollectionReusableView *reusableview = nil; NSLog(@"kind = %@", kind); if (kind == UICollectionElementKindSectionHeader){ myHeadView *headerV = (myHeadView *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"HeadView" forIndexPath:indexPath]; [headerV setTextTitle]; reusableview = headerV; } return reusableview; } @end