UICollectionView的头部悬停效果

本文介绍如何使用UICollectionViewFlowLayout实现UICollectionView头部视图的悬停效果,包括重写布局属性和调整头部视图位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

帮朋友协议一个小demo,集合视图的头部悬停效果。顺便学习一下:都知道在列表中的头部视图是可以悬停的。这个效果是很常用的。那么集合视图如何实现头部悬停呢???

其实就是----》UICollectionViewFlowLayout他咯,因为所有的集合视图布局都是通过它来产生各种效果的 包括瀑布流,环形 矩形等效果,那么我们就重写这个类。

重写之前我们先看一下效果:

首先是实现有头部视图的集合视图:


//宏定义宽高

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width

#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height



@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>


@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;


@end


static NSString *const CustomCollectionHeadId = @"CustomCollectionReusableViewId";

static NSString *const cellId = @"CustomCollectionViewCellId";


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

     

    UICollectionViewFlowLayout *flat = [[UICollectionViewFlowLayout alloc]init];

    flat.scrollDirection = UICollectionViewScrollDirectionVertical;

    [self.collectionView setCollectionViewLayout:flat];

    [self.collectionView registerNib:[UINib nibWithNibName:@"CustomCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:CustomCollectionHeadId];

    [self.collectionView registerNib:[UINib nibWithNibName:@"CustomCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:cellId];

}


#pragma mark collectionViewDelegate

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView

{

    return 1;

}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

{

    return 100;

}

//设置元素大小

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{

    

    return CGSizeMake(SCREEN_WIDTH/2 - 5, 300);

}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath

{

    CustomCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellId forIndexPath:indexPath];

    cell.backgroundColor = [UIColor yellowColor];

    NSInteger tag = 10;

    UILabel *label = (UILabel *)[cell.contentView viewWithTag:tag];

    if (label == nil) {

        label = [[UILabel alloc] init];

        label.tag = tag;

        label.font = [UIFont systemFontOfSize:15];

        [cell.contentView addSubview:label];

    }

    

    label.text = [NSString stringWithFormat:@"%@item",@(indexPath.row)];

    [label sizeToFit];

    return cell;

    

}



-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath

{

    //UICollectionView被选中时调用的方法

}


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

{

    CustomCollectionReusableView *headReusableView;

    //此处是headerView

    if (kind == UICollectionElementKindSectionHeader) {

        headReusableView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:CustomCollectionHeadId forIndexPath:indexPath];

        headReusableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 250);

    }

    return headReusableView;

}

//执行的 headerView 代理  返回 headerView 的高度

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

{

        return CGSizeMake(SCREEN_WIDTH, 250);

}

然后才是悬停效果的实现:继承UICollectionViewFlowLayout

#import "HeaderFlowLayout.h"


@implementation HeaderFlowLayout


-(instancetype)init

{

    self = [super init];

    if (self)

    {

    }

    return self;

}

/*

 // 作用:返回指定区域的cell布局对象

 // 什么时候调用:指定新的区域的时候调用

 */

- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect

{

    //UICollectionViewLayoutAttributes:我称它为collectionView中的item(包括cellheaderfooter这些)的《结构信息》

    //截取到父类所返回的数组(里面放的是当前屏幕所能展示的item的结构信息),并转化成不可变数组

    NSMutableArray *superArray = [[super layoutAttributesForElementsInRect:rect] mutableCopy];

    //创建存索引的数组,无符号(正整数),无序(不能通过下标取值),不可重复(重复的话会自动过滤)

    NSMutableIndexSet *noneHeaderSections = [NSMutableIndexSet indexSet];

    //遍历superArray,得到一个当前屏幕中所有的section数组

    for (UICollectionViewLayoutAttributes *attributes in superArray)

    {

        //如果当前的元素分类是一个cell,将cell所在的分区section加入数组,重复的话会自动过滤

        if (attributes.representedElementCategory == UICollectionElementCategoryCell)

        {

            [noneHeaderSections addIndex:attributes.indexPath.section];

        }

    }

    //遍历superArray,将当前屏幕中拥有的headersection从数组中移除,得到一个当前屏幕中没有headersection数组

    //正常情况下,随着手指往上移,header脱离屏幕会被系统回收而cell尚在,也会触发该方法

    for (UICollectionViewLayoutAttributes *attributes in superArray)

    {

        //如果当前的元素是一个header,将header所在的section从数组中移除

        if ([attributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader])

        {

            [noneHeaderSections removeIndex:attributes.indexPath.section];

        }

    }

    

    //遍历当前屏幕中没有headersection数组

    [noneHeaderSections enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop){

        

        //取到当前section中第一个itemindexPath

        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:idx];

        //获取当前section在正常情况下已经离开屏幕的header结构信息

        UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:indexPath];

        

        //如果当前分区确实有因为离开屏幕而被系统回收的header

        if (attributes)

        {

            //将该header结构信息重新加入到superArray中去

            [superArray addObject:attributes];

        }

    }];

    

    //遍历superArray,改变header结构信息中的参数,使它可以在当前section还没完全离开屏幕的时候一直显示

    for (UICollectionViewLayoutAttributes *attributes in superArray) {

        //如果当前itemheader

        if ([attributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader])

        {

            //得到当前header所在分区的cell的数量

            NSInteger numberOfItemsInSection = [self.collectionView numberOfItemsInSection:attributes.indexPath.section];

            //得到第一个itemindexPath

            NSIndexPath *firstItemIndexPath = [NSIndexPath indexPathForItem:0 inSection:attributes.indexPath.section];

            //得到最后一个itemindexPath

            NSIndexPath *lastItemIndexPath = [NSIndexPath indexPathForItem:MAX(0, numberOfItemsInSection-1) inSection:attributes.indexPath.section];

            //得到第一个item和最后一个item的结构信息

            UICollectionViewLayoutAttributes *firstItemAttributes, *lastItemAttributes;

            if (numberOfItemsInSection>0)

            {

                //cell有值,则获取第一个cell和最后一个cell的结构信息

                firstItemAttributes = [self layoutAttributesForItemAtIndexPath:firstItemIndexPath];

                lastItemAttributes = [self layoutAttributesForItemAtIndexPath:lastItemIndexPath];

            }else

            {

                //cell没值,就新建一个UICollectionViewLayoutAttributes

                firstItemAttributes = [UICollectionViewLayoutAttributes new];

                //然后模拟出在当前分区中的唯一一个cellcellheader的下面,高度为0,还与header隔着可能存在的sectionInsettop

                CGFloat y = CGRectGetMaxY(attributes.frame)+self.sectionInset.top;

                firstItemAttributes.frame = CGRectMake(0, y, 0, 0);

                //因为只有一个cell,所以最后一个cell等于第一个cell

                lastItemAttributes = firstItemAttributes;

            }

            

            //获取当前headerframe

            CGRect rect = attributes.frame;

            

            //当前的滑动距离 + 因为导航栏产生的偏移量,默认为64(如果app需求不同,需自己设置)

            CGFloat offset = self.collectionView.contentOffset.y + _naviHeight;

            //第一个celly - 当前header的高度 - 可能存在的sectionInsettop

            CGFloat headerY = firstItemAttributes.frame.origin.y - rect.size.height - self.sectionInset.top;

            

            //哪个大取哪个,保证header悬停

            //针对当前header基本上都是offset更加大,针对下一个header则会是headerY大,各自处理

            CGFloat maxY = MAX(offset,headerY);

            

            //最后一个celly + 最后一个cell的高度 + 可能存在的sectionInsetbottom - 当前header的高度

            //当当前sectionfooter或者下一个sectionheader接触到当前header的底部,计算出的headerMissingY即为有效值

            CGFloat headerMissingY = CGRectGetMaxY(lastItemAttributes.frame) + self.sectionInset.bottom - rect.size.height;

            

            //recty赋新值,因为在最后消失的临界点要跟谁消失,所以取小

            rect.origin.y = MIN(maxY,headerMissingY);

            //header的结构信息的frame重新赋值

            attributes.frame = rect;

            

            //如果按照正常情况下,header离开屏幕被系统回收,而header的层次关系又与cell相等,如果不去理会,会出现cellheader上面的情况

            //通过打印可以知道cell的层次关系zIndex数值为0,我们可以将headerzIndex设置成1,如果不放心,也可以将它设置成非常大,这里随便填了个7

            attributes.zIndex = 7;

        }

    }

    //转换回不可变数组,并返回

    return [superArray copy];

    

}


//return YES;表示一旦滑动就实时调用上面这个layoutAttributesForElementsInRect:方法

- (BOOL) shouldInvalidateLayoutForBoundsChange:(CGRect)newBound

{

    return YES;

}

然后只需要改动一点:


OK!!!


















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值