在使用collectionView時,想做個分組,需要顯示header,但是發現,顯示header和footer的回調方法不執行,不懈追蹤,終於找到原因!!!!!!!
layout.headerReferenceSize = CGSizeMake(100, 22);//重要,寫上該行代碼后,顯示header和footer的回調方法成功執行,最終成功顯示header
現在記錄一下CollectionView的使用過程
初始化:
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
[layout setScrollDirection:UICollectionViewScrollDirectionVertical];
layout.headerReferenceSize = CGSizeMake(100, 22);
UICollectionView *dataListcollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64,self.view.frame.size.width,260) collectionViewLayout:layout];
[dataListcollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];//注冊cell
[dataListcollectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];//注冊header的view
dataListcollectionView.delegate = self;
dataListcollectionView.dataSource = self;
[self.view addSubview:dataListcollectionView];
設置代理方法
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [dataArray count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
return cell;
}
//顯示header和footer的回調方法
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
if (kind == UICollectionElementKindSectionHeader)
{//如果想要自定義header,只需要定義UICollectionReusableView的子類A,然后在該處使用,注意AIdentifier要設為注冊的字符串,此處為“header”
UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
return view;
}
return nil;
}
//設置元素大小
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(100,100);
}