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;

}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM