您的位置:

深入探究UICollectionHeaderView

一、UICollectionHeaderView的作用

在使用UICollectionViewController时, 会经常使用到UICollectionHeaderView, 它是UICollectionView的一种特殊的区头视图,用于显示区头内容。

在实际开发中, 可以利用UICollectionHeaderView实现一些突出的效果, 比如插入一个广告条、置顶一个重要的导航等。

二、UICollectionHeaderView的使用方法

UICollectionHeaderView的使用是比较简单的:

首先要自定义一个View,继承于UICollectionReusableView, 并实现其中的初始化函数。

 - (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        //TODO: Initialization code
    }
    return self;
}

在UICollectionView中,可以通过注册区头视图的方法注册此View。

 [self.collectionView registerClass:[CustomHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEADERVIEWIDENTIFIER];

或者在Interface Builder中设置UICollectionView的Header的自定义class, 然后在自定义View中实现渲染和自定义视图的方法。

三、UICollectionHeaderView的悬停效果实现方法

当UICollectionHeaderView出现时如果不希望它随CollectionView一起滚动, 而希望它固定在顶部, 并且随着滚动,不断更新headerView的位置和状态, 这种实现称为悬停效果。

实现这种悬停效果的主要思路:在CollectionView滚动的时候,监听当前滚动的偏移量,然后根据偏移量,计算当前headerView需要达到的位置,从而进行动态的变化。

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    //获取当前headerView的frame
    CGRect headerFrame = self.headerView.frame;
    
    //如果headerView还处于CollectionView的顶部
    if (scrollView.contentOffset.y <= -headerFrame.size.height) {
        headerFrame.origin.y = scrollView.contentOffset.y;
        self.headerView.frame = headerFrame;
    }
    //如果headerView离开了CollectionView的顶部
    else {
        headerFrame.origin.y = MAX(-scrollView.contentOffset.y-headerFrame.size.height, -headerFrame.size.height);
        self.headerView.frame = headerFrame;
    }
}

四、UICollectionHeaderView的重复利用

由于UICollectionHeaderView可能存在多个,因此对headerView的重用是必要的。由于要重复利用,我们可以使用iOS的默认重复利用机制,即buffer pool。

UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:HEADERVIEWIDENTIFIER forIndexPath:indexPath];

在调用dequeueReusableSupplementaryViewOfKind时,系统会在buffer pool中寻找与HEADERVIEWIDENTIFIER一样的headerView,如果找不到则会使用HEADERVIEWIDENTIFIER注册的headerView进行新的创建。如果有则系统会返回重复利用的headerView。

五、UICollectionHeaderView的动画特效实现

UICollectionHeaderView还能够实现一些动画特效,比如拉伸动画、放大动画等,让CollectionView看起来更加生动。

实现这些动画特效的关键步骤是:在CollectionView滚动的时候,监听当前滚动的偏移量,然后根据偏移量计算出需要展示的动画效果(UIView的transform动画EQ)。

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat yOffset = scrollView.contentOffset.y;
    if (yOffset < 0) {
        CGFloat factor = MAX(ABS(yOffset/header_height), 0.0001);
        CGFloat f = (header_height*yOffset+header_height)/header_height;
        CGAffineTransform t = CGAffineTransformMakeScale(f, f);
        self.headerView.imageView.transform = t;
    }
}

六、UICollectionHeaderView的优化

当数据量过大时,headerView的重复利用效率会下降,这时需要进行优化措施。

优化措施:使用离屏渲染,将常用的元素(比如label、imageView等)预先缓存,少做计算即可。

七、总结

UICollectionHeaderView的悬停、动画特效等实现方法都是围绕着监听当前CollectionView的offset来进行的,对headerView的重复利用和离屏渲染的优化也是需要注意的。在实际项目中,我们可以将上述方法综合运用,让UICollectionHeaderView展现更加丰富的效果。