iOS开发之UICollectionView的headerView实现与TableView一样的漂浮效果

使用 点击这里查看

这次主要是写关于UICollectionView的头部使用还有漂浮效果
相关代码请参考本人github上的代码 点击这里进入源代码
在UICollectionViewFlowLayout里面实现的代码是没有依赖和耦合性的,如果项目需要可以直接导入修改layout就行了


collectionview头部漂浮效果.gif

介绍UICollectionView的头部的基本用法

#UICollectionView的头部视图也需要注册
//注册头部视图
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([JHHeaderReusableView class]) bundle:nil] 
forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kHeaderID];

#注意: 这里的JHHeaderReusableView 是我自定义的头部视图的类
#头部视图的类自定义必须继承UICollectionReusableView
#我上面的是通过xib 所以注册的时候需要注意 (一般界面没上面大的改变推荐使用xib实现)

#下面是头部视图的代理方法:
#pragma mark - 头部或者尾部视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //如果是头部视图 (因为这里的kind 有头部和尾部所以需要判断  默认是头部,严谨判断比较好)
/*
  JHHeaderReusableView 头部的类
  kHeaderID  重用标识
*/
    if (kind == UICollectionElementKindSectionHeader) {
        JHHeaderReusableView *headerRV = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:kHeaderID forIndexPath:indexPath];
        headerRV.homeModel = self.bodyArray[indexPath.section];
        return headerRV;

    }else //有兴趣的也可以添加尾部视图
    {
        return nil;
    }
}

#在JHHeaderReusableView里面实现你需要的头部视图的内容

上面的方法已经可以实现头部视图

下面的效果是使头部视图的漂浮效果

因为collectionViewd的具体布局是UICollectionViewFlowLayout 决定的  
所以创建一个JHHeaderFlowLayout继承于UICollectionViewFlowLayout

#具体的代码实现


#pragma mark - 初始化
-(instancetype)init
{
    self = [super init];
    if (self)
    {
        _naviHeight = 0.0;
    }
    return self;
}
/*

 // 作用:返回指定区域的cell布局对象
 // 什么时候调用:指定新的区域的时候调用 
 (<__kindof UICollectionViewLayoutAttributes *>   iOS9之后的泛型 )
 - (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
 */

/** iOS9 之前的写法 作用第24行代码有写*/
//UICollectionViewLayoutAttributes:我称它为collectionView中的item(包括cell和header、footer这些)的《结构信息》
- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect
{

    //截取到父类所返回的数组(里面放的是当前屏幕所能展示的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,将当前屏幕中拥有的header的section从数组中移除,得到一个当前屏幕中没有header的section数组
    //正常情况下,随着手指往上移,header脱离屏幕会被系统回收而cell尚在,也会触发该方法
    for (UICollectionViewLayoutAttributes *attributes in superArray)
    {
        //如果当前的元素是一个header,将header所在的section从数组中移除
        if ([attributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader])
        {
            [noneHeaderSections removeIndex:attributes.indexPath.section];
        }
    }

    //遍历当前屏幕中没有header的section数组
    [noneHeaderSections enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop){

        //取到当前section中第一个item的indexPath
        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) {

        //如果当前item是header
        if ([attributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader])
        {
            //得到当前header所在分区的cell的数量
            NSInteger numberOfItemsInSection = [self.collectionView numberOfItemsInSection:attributes.indexPath.section];
            //得到第一个item的indexPath
            NSIndexPath *firstItemIndexPath = [NSIndexPath indexPathForItem:0 inSection:attributes.indexPath.section];
            //得到最后一个item的indexPath
            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];
                //然后模拟出在当前分区中的唯一一个cell,cell在header的下面,高度为0,还与header隔着可能存在的sectionInset的top
                CGFloat y = CGRectGetMaxY(attributes.frame)+self.sectionInset.top;
                firstItemAttributes.frame = CGRectMake(0, y, 0, 0);
                //因为只有一个cell,所以最后一个cell等于第一个cell
                lastItemAttributes = firstItemAttributes;
            }

            //获取当前header的frame
            CGRect rect = attributes.frame;

            //当前的滑动距离 + 因为导航栏产生的偏移量,默认为64(如果app需求不同,需自己设置)
            CGFloat offset = self.collectionView.contentOffset.y + _naviHeight;
            //第一个cell的y值 - 当前header的高度 - 可能存在的sectionInset的top
            CGFloat headerY = firstItemAttributes.frame.origin.y - rect.size.height - self.sectionInset.top;

            //哪个大取哪个,保证header悬停
            //针对当前header基本上都是offset更加大,针对下一个header则会是headerY大,各自处理
            CGFloat maxY = MAX(offset,headerY);

            //最后一个cell的y值 + 最后一个cell的高度 + 可能存在的sectionInset的bottom - 当前header的高度
            //当当前section的footer或者下一个section的header接触到当前header的底部,计算出的headerMissingY即为有效值
            CGFloat headerMissingY = CGRectGetMaxY(lastItemAttributes.frame) + self.sectionInset.bottom - rect.size.height;

            //给rect的y赋新值,因为在最后消失的临界点要跟谁消失,所以取小
            rect.origin.y = MIN(maxY,headerMissingY);
            //给header的结构信息的frame重新赋值
            attributes.frame = rect;

            //如果按照正常情况下,header离开屏幕被系统回收,而header的层次关系又与cell相等,如果不去理会,会出现cell在header上面的情况
            //通过打印可以知道cell的层次关系zIndex数值为0,我们可以将header的zIndex设置成1,如果不放心,也可以将它设置成非常大,这里随便填了个7
            attributes.zIndex = 7;
        }
    }

    //转换回不可变数组,并返回
    return [superArray copy];

}

//return YES;表示一旦滑动就实时调用上面这个layoutAttributesForElementsInRect:方法
- (BOOL) shouldInvalidateLayoutForBoundsChange:(CGRect)newBound
{
    return YES;
}

UICollectionView是一个很强大的控件,还有很多强大的功能等着被挖掘, 希望在学习的道路上可以一起跟大牛的余香找点感觉 嘻嘻....

具体代码点击后面 点击此处跳转到github源码


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
iOS 开发中,TableView 是一个非常重要的视图控件,用于展示大量数据。而 TableView 中的 HeaderView 和 FooterView 也是非常重要的组件,可以用于展示一些额外的信息或者操作按钮。在 TableView 中,我们可以通过注册重用标识符来复用 Cell,但是对于 HeaderView 和 FooterView 却没有提供类似的注册方法。本文将介绍如何在 TableView 中循环利用 HeaderView,并且还会介绍如何自定义 HeaderView。 ## 循环利用 TableView 中的 HeaderViewTableView 中,我们可以通过以下方法来设置 HeaderView: ``` - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.bounds.size.width, 44)]; headerView.backgroundColor = [UIColor grayColor]; return headerView; } - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section { return 44; } ``` 上面的代码中,我们通过实现 `tableView:viewForHeaderInSection:` 方法来设置 HeaderView 的内容和样式,通过实现 `tableView:heightForHeaderInSection:` 方法来设置 HeaderView 的高度。但是如果我们在 TableView 中有很多组数据,每次都创建一个新的 HeaderView 会非常消耗性能,因此我们需要对 HeaderView 进行循环利用。 循环利用 HeaderView实现方法非常简单,我们只需要在 TableView 的代理方法中通过 `dequeueReusableHeaderFooterViewWithIdentifier:` 方法来获取 HeaderView,如果获取到的 HeaderView 为 nil,就创建一个新的 HeaderView,否则就返回重用的 HeaderView。 ``` - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { static NSString *headerIdentifier = @"headerIdentifier"; UITableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerIdentifier]; if (!headerView) { headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:headerIdentifier]; headerView.contentView.backgroundColor = [UIColor grayColor]; } return headerView; } ``` 上面的代码中,我们首先定义一个静态的重用标识符 `headerIdentifier`,然后通过 `dequeueReusableHeaderFooterViewWithIdentifier:` 方法获取重用的 HeaderView。如果获取到的 HeaderView 为 nil,我们就创建一个新的 HeaderView,并且设置它的重用标识符为 `headerIdentifier`。最后,我们设置 HeaderView 的背景颜色,并且返回 HeaderView。 ## 自定义 TableView 中的 HeaderView 除了循环利用 HeaderView,我们还可以自定义 HeaderView。自定义 HeaderView 的方法与自定义 Cell 的方法类似,我们需要在 XIB 或者代码中创建一个自定义的 HeaderView,然后在 TableView 的代理方法中返回它。 ### 在 XIB 中创建自定义 HeaderView 在 XIB 中创建自定义 HeaderView 的方法非常简单,我们只需要创建一个新的 XIB 文件,然后在 XIB 中添加一个 UIView,将它的 Class 设置为 UITableViewHeaderFooterView,接着就可以在 XIB 中自定义 HeaderView 的内容和样式了。 创建完成后,我们需要在代码中注册这个 XIB 文件,并且设置它的重用标识符。在 TableView 的初始化方法中,我们可以通过以下方法来注册 XIB 文件: ``` UINib *headerNib = [UINib nibWithNibName:@"HeaderView" bundle:nil]; [tableView registerNib:headerNib forHeaderFooterViewReuseIdentifier:@"headerIdentifier"]; ``` 上面的代码中,我们首先通过 `nibWithNibName:bundle:` 方法加载 XIB 文件,然后通过 `registerNib:forHeaderFooterViewReuseIdentifier:` 方法注册 XIB 文件,并且设置它的重用标识符为 `headerIdentifier`。 最后,在 TableView 的代理方法中,我们可以通过以下方法来获取自定义的 HeaderView: ``` - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { static NSString *headerIdentifier = @"headerIdentifier"; UITableViewHeaderFooterView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerIdentifier]; return headerView; } ``` ### 在代码中创建自定义 HeaderView 在代码中创建自定义 HeaderView 的方法也非常简单,我们只需要创建一个继承自 UITableViewHeaderFooterView 的类,然后在这个类中实现自定义 HeaderView 的内容和样式。 ``` @interface CustomHeaderView : UITableViewHeaderFooterView @property (nonatomic, strong) UILabel *titleLabel; @end @implementation CustomHeaderView - (instancetype)initWithReuseIdentifier:(NSString *)reuseIdentifier { if (self = [super initWithReuseIdentifier:reuseIdentifier]) { self.contentView.backgroundColor = [UIColor grayColor]; self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, self.contentView.bounds.size.width - 20, self.contentView.bounds.size.height)]; self.titleLabel.font = [UIFont systemFontOfSize:16]; self.titleLabel.textColor = [UIColor whiteColor]; [self.contentView addSubview:self.titleLabel]; } return self; } @end ``` 上面的代码中,我们创建了一个名为 `CustomHeaderView` 的类,继承自 UITableViewHeaderFooterView。在这个类的初始化方法中,我们设置了 HeaderView 的背景颜色,并且创建了一个 UILabel 来显示标题,最后将它添加到 HeaderView 的 contentView 上。 创建完成后,我们需要在代码中注册这个自定义 HeaderView,并且设置它的重用标识符。在 TableView 的初始化方法中,我们可以通过以下方法来注册自定义 HeaderView: ``` [tableView registerClass:[CustomHeaderView class] forHeaderFooterViewReuseIdentifier:@"headerIdentifier"]; ``` 上面的代码中,我们通过 `registerClass:forHeaderFooterViewReuseIdentifier:` 方法注册自定义 HeaderView,并且设置它的重用标识符为 `headerIdentifier`。 最后,在 TableView 的代理方法中,我们可以通过以下方法来获取自定义的 HeaderView: ``` - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section { static NSString *headerIdentifier = @"headerIdentifier"; CustomHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerIdentifier]; headerView.titleLabel.text = [NSString stringWithFormat:@"Header %ld", section]; return headerView; } ``` 上面的代码中,我们首先定义一个静态的重用标识符 `headerIdentifier`,然后通过 `dequeueReusableHeaderFooterViewWithIdentifier:` 方法获取自定义的 HeaderView,并且设置它的标题为 `Header section`。最后,我们返回自定义的 HeaderView。 总结 在本文中,我们介绍了如何在 TableView 中循环利用 HeaderView,并且还介绍了如何自定义 HeaderView。循环利用 HeaderView 可以提高 TableView 的性能,自定义 HeaderView 可以让我们更加灵活地控制 HeaderView 的样式和内容。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值