1.新建2個view繼承自UICollectionReusableView
2.view里實現你想展現的控件
3.viewdidload里實現
[self.collectionView registerClass:[HeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head"];
[self.collectionView registerClass:[FootView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"foot"];
4.實現方法:
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
if (kind == UICollectionElementKindSectionHeader) {
HeadView * headerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"head" forIndexPath:indexPath];
headerView.imageView.image=[UIImage imageNamed:@"xxx"];
return headerView;
}
FootView * footerView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"foot" forIndexPath:indexPath];
footerView.imageView.image=[UIImage imageNamed:@"xxx"];
return footerView;
}
...........................................................
用xib來實現方法如下:
//注冊headerView Nib的view需要繼承UICollectionReusableView
[self.collectionView registerNib:[UINib nibWithNibName:@"xxx" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head"];
//注冊footerView Nib的view需要繼承UICollectionReusableView
[self.collectionView registerNib:[UINib nibWithNibName:@"xxx" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"foot"];
實現方法:
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
NSString * reuseIdentifier;
if ([kind isEqualToString: UICollectionElementKindSectionFooter ]){
reuseIdentifier = @"foot";
}else{
reuseIdentifier = @"head";
}
UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind :kind withReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
//控件綁定tag
UILabel *label = (UILabel *)[view viewWithTag:1];
if ([kind isEqualToString:UICollectionElementKindSectionHeader]){
label.text = [NSString stringWithFormat:@"這是header:%ld",(long)indexPath.section];
}
else if ([kind isEqualToString:UICollectionElementKindSectionFooter]){
view.backgroundColor = [UIColor lightGrayColor];
label.text = [NSString stringWithFormat:@"這是footer:%ld",(long)indexPath.section];
}
return view;
}