关键代码如下:
static NSString *headerViewIdentifier = @"hederview";
-(void)addCollectionView
{
_layout = [[UICollectionViewFlowLayout alloc]init];
_layout.minimumLineSpacing=20; //设置每一行的间距
_layout.itemSize=CGSizeMake((kDeviceWidth - 38) / 2, (kDeviceWidth - 38) / 2 + 50 ); //设置每个单元格的大小
_layout.sectionInset=UIEdgeInsetsMake(20, 14, 20, 14);//设置间隔
_layout.headerReferenceSize=CGSizeMake(self.view.frame.size.width,60); //设置collectionView头视图的大小
_collectionView =[[UICollectionView alloc]initWithFrame:self.view.bounds collectionViewLayout:_layout];
_collectionView.delegate=self;
_collectionView.dataSource=self;
self.defaultView.hidden=YES;
_collectionView.frame=self.view.bounds;
_collectionView.backgroundView=self.defaultView;
_collectionView.backgroundColor=kColorTextGray_246;
//注册cell单元格
[_collectionView registerClass:[DiscoveryCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
//注册头视图
[_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:headerViewIdentifier];
[self.view addSubview:_collectionView];
}
// 返回头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
//如果是头视图
if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
UICollectionReusableView *header=[collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:headerViewIdentifier forIndexPath:indexPath];
//头视图添加view
[header addSubview:self.scrollView];
[header addSubview:self.pageControl];
return header;
}
return nil;
}