iOS collectionView自定义head和foot

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;

}

posted @ 2015-07-21 15:07  tongyuling  阅读(2529)  评论(0)    收藏  举报