关于UICollectionViewController的header和foot视图

随便商城项目的慢慢推进,以前慢慢生疏的控件又必须要再一次拾起,今天遇到的问题是怎么给collectionViewController添加一个label

在网上找了许多的方法,其中很多基本上都是说在storyBoard中先拉出header和foot的视图,然后在到

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath 这个方法中来进行配置,(网上方法很多,这个就不说了)

现在就来说一说纯代码该怎么样进行配置呢?当然,核心api还是上面这个,但是需要在前期配置一下

1.创建继承自UICollectionReusableView的类.h

@interface LIUHeaderCollectionReusableView : UICollectionReusableView

@property(nonatomic,strong)UILabel *label;

@end

.m 发现register 中得dequeue是实现这个方法

- (instancetype)initWithFrame:(CGRect)frame {

    if (self = [super initWithFrame:frame]) {

        [self addSubview:self.label];

    }

    return self;

}

2.在collection中注册

//注册headerView

    [self registerClass:[LIUHeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];

    [self registerClass:[LIUHeaderCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"foot"];

 3.在上面所说的api中dequeue

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{

    

    NSString *reuseIdentifier;

    if ([kind isEqualToString: UICollectionElementKindSectionFooter]){

        reuseIdentifier = @"foot";

    }else{

        reuseIdentifier = @"header";

    }

        LIUHeaderCollectionReusableView *view =  (LIUHeaderCollectionReusableView *)[collectionView dequeueReusableSupplementaryViewOfKind :kind   withReuseIdentifier:reuseIdentifier   forIndexPath:indexPath];

    if ([kind isEqualToString:UICollectionElementKindSectionHeader]){

        //view.backgroundColor = [UIColor greenColor];

        //1.拿到section对应的字典

        NSString *text = self.allKeys[indexPath.section];

    view.label.text = text;

    }

    else if ([kind isEqualToString:UICollectionElementKindSectionFooter]){

        view.backgroundColor = [UIColor lightGrayColor];

        view.label.text = [NSString stringWithFormat:@"这是footer:%ld",(long)indexPath.section];

    }

    return view;

 }

 

4.就是要回答header和foot的size,要不是不会显示的,如 我这个是不要foot的

//foot不要

//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {

//    return CGSizeMake(self.bounds.size.width, 30);

//}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {

    return CGSizeMake(self.bounds.size.width, 30);

}

 

posted on 2015-06-18 16:20  飞羽的幸福  阅读(240)  评论(0编辑  收藏  举报

导航