UICollectionView實現(xiàn)頭部漂浮的效果

如果對collectionView還不了解的,可以先看看我上次寫的關(guān)于UICollectionView的基本使用 點擊這里查看

這次主要是寫關(guān)于UICollectionView的頭部使用還有漂浮效果
相關(guān)代碼請參考本人github上的代碼 點擊這里進(jìn)入源代碼
在UICollectionViewFlowLayout里面實現(xiàn)的代碼是沒有依賴和耦合性的,如果項目需要可以直接導(dǎo)入修改layout就行了

collectionview頭部漂浮效果.gif

介紹UICollectionView的頭部的基本用法

#UICollectionView的頭部視圖也需要注冊
//注冊頭部視圖
    [self.collectionView registerNib:[UINib nibWithNibName:NSStringFromClass([JHHeaderReusableView class]) bundle:nil] 
forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kHeaderID];

#注意: 這里的JHHeaderReusableView 是我自定義的頭部視圖的類
#頭部視圖的類自定義必須繼承UICollectionReusableView
#我上面的是通過xib 所以注冊的時候需要注意 (一般界面沒上面大的改變推薦使用xib實現(xiàn))

#下面是頭部視圖的代理方法:
#pragma mark - 頭部或者尾部視圖
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    //如果是頭部視圖 (因為這里的kind 有頭部和尾部所以需要判斷  默認(rèn)是頭部,嚴(yán)謹(jǐn)判斷比較好)
/*
  JHHeaderReusableView 頭部的類
  kHeaderID  重用標(biāo)識
*/
    if (kind == UICollectionElementKindSectionHeader) {
        JHHeaderReusableView *headerRV = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:kHeaderID forIndexPath:indexPath];
        headerRV.homeModel = self.bodyArray[indexPath.section];
        return headerRV;
        
    }else //有興趣的也可以添加尾部視圖
    {
        return nil;
    }
}

#在JHHeaderReusableView里面實現(xiàn)你需要的頭部視圖的內(nèi)容

上面的方法已經(jīng)可以實現(xiàn)頭部視圖

下面的效果是使頭部視圖的漂浮效果

因為collectionViewd的具體布局是UICollectionViewFlowLayout 決定的  
所以創(chuàng)建一個JHHeaderFlowLayout繼承于UICollectionViewFlowLayout

#具體的代碼實現(xiàn)
 

#pragma mark - 初始化
-(instancetype)init
{
    self = [super init];
    if (self)
    {
        _naviHeight = 0.0;
    }
    return self;
}
/*
 
 // 作用:返回指定區(qū)域的cell布局對象
 // 什么時候調(diào)用:指定新的區(qū)域的時候調(diào)用 
 (<__kindof UICollectionViewLayoutAttributes *>   iOS9之后的泛型 )
 - (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
 */

/** iOS9 之前的寫法 作用第24行代碼有寫*/
//UICollectionViewLayoutAttributes:我稱它為collectionView中的item(包括cell和header、footer這些)的《結(jié)構(gòu)信息》
- (NSArray *) layoutAttributesForElementsInRect:(CGRect)rect
{
    
    //截取到父類所返回的數(shù)組(里面放的是當(dāng)前屏幕所能展示的item的結(jié)構(gòu)信息),并轉(zhuǎn)化成不可變數(shù)組
    NSMutableArray *superArray = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
    
    //創(chuàng)建存索引的數(shù)組,無符號(正整數(shù)),無序(不能通過下標(biāo)取值),不可重復(fù)(重復(fù)的話會自動過濾)
    NSMutableIndexSet *noneHeaderSections = [NSMutableIndexSet indexSet];
    //遍歷superArray,得到一個當(dāng)前屏幕中所有的section數(shù)組
    for (UICollectionViewLayoutAttributes *attributes in superArray)
    {
        //如果當(dāng)前的元素分類是一個cell,將cell所在的分區(qū)section加入數(shù)組,重復(fù)的話會自動過濾
        if (attributes.representedElementCategory == UICollectionElementCategoryCell)
        {
            [noneHeaderSections addIndex:attributes.indexPath.section];
        }
    }
    
    //遍歷superArray,將當(dāng)前屏幕中擁有的header的section從數(shù)組中移除,得到一個當(dāng)前屏幕中沒有header的section數(shù)組
    //正常情況下,隨著手指往上移,header脫離屏幕會被系統(tǒng)回收而cell尚在,也會觸發(fā)該方法
    for (UICollectionViewLayoutAttributes *attributes in superArray)
    {
        //如果當(dāng)前的元素是一個header,將header所在的section從數(shù)組中移除
        if ([attributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader])
        {
            [noneHeaderSections removeIndex:attributes.indexPath.section];
        }
    }
    
    //遍歷當(dāng)前屏幕中沒有header的section數(shù)組
    [noneHeaderSections enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop){
        
        //取到當(dāng)前section中第一個item的indexPath
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:idx];
        //獲取當(dāng)前section在正常情況下已經(jīng)離開屏幕的header結(jié)構(gòu)信息
        UICollectionViewLayoutAttributes *attributes = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:indexPath];
        
        //如果當(dāng)前分區(qū)確實有因為離開屏幕而被系統(tǒng)回收的header
        if (attributes)
        {
            //將該header結(jié)構(gòu)信息重新加入到superArray中去
            [superArray addObject:attributes];
        }
    }];
    
    //遍歷superArray,改變header結(jié)構(gòu)信息中的參數(shù),使它可以在當(dāng)前section還沒完全離開屏幕的時候一直顯示
    for (UICollectionViewLayoutAttributes *attributes in superArray) {
        
        //如果當(dāng)前item是header
        if ([attributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader])
        {
            //得到當(dāng)前header所在分區(qū)的cell的數(shù)量
            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的結(jié)構(gòu)信息
            UICollectionViewLayoutAttributes *firstItemAttributes, *lastItemAttributes;
            if (numberOfItemsInSection>0)
            {
                //cell有值,則獲取第一個cell和最后一個cell的結(jié)構(gòu)信息
                firstItemAttributes = [self layoutAttributesForItemAtIndexPath:firstItemIndexPath];
                lastItemAttributes = [self layoutAttributesForItemAtIndexPath:lastItemIndexPath];
            }else
            {
                //cell沒值,就新建一個UICollectionViewLayoutAttributes
                firstItemAttributes = [UICollectionViewLayoutAttributes new];
                //然后模擬出在當(dāng)前分區(qū)中的唯一一個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;
            }
            
            //獲取當(dāng)前header的frame
            CGRect rect = attributes.frame;
            
            //當(dāng)前的滑動距離 + 因為導(dǎo)航欄產(chǎn)生的偏移量,默認(rèn)為64(如果app需求不同,需自己設(shè)置)
            CGFloat offset = self.collectionView.contentOffset.y + _naviHeight;
            //第一個cell的y值 - 當(dāng)前header的高度 - 可能存在的sectionInset的top
            CGFloat headerY = firstItemAttributes.frame.origin.y - rect.size.height - self.sectionInset.top;
            
            //哪個大取哪個,保證header懸停
            //針對當(dāng)前header基本上都是offset更加大,針對下一個header則會是headerY大,各自處理
            CGFloat maxY = MAX(offset,headerY);
            
            //最后一個cell的y值 + 最后一個cell的高度 + 可能存在的sectionInset的bottom - 當(dāng)前header的高度
            //當(dāng)當(dāng)前section的footer或者下一個section的header接觸到當(dāng)前header的底部,計算出的headerMissingY即為有效值
            CGFloat headerMissingY = CGRectGetMaxY(lastItemAttributes.frame) + self.sectionInset.bottom - rect.size.height;
            
            //給rect的y賦新值,因為在最后消失的臨界點要跟誰消失,所以取小
            rect.origin.y = MIN(maxY,headerMissingY);
            //給header的結(jié)構(gòu)信息的frame重新賦值
            attributes.frame = rect;
            
            //如果按照正常情況下,header離開屏幕被系統(tǒng)回收,而header的層次關(guān)系又與cell相等,如果不去理會,會出現(xiàn)cell在header上面的情況
            //通過打印可以知道cell的層次關(guān)系zIndex數(shù)值為0,我們可以將header的zIndex設(shè)置成1,如果不放心,也可以將它設(shè)置成非常大,這里隨便填了個7
            attributes.zIndex = 7;
        }
    }
    
    //轉(zhuǎn)換回不可變數(shù)組,并返回
    return [superArray copy];
    
}

//return YES;表示一旦滑動就實時調(diào)用上面這個layoutAttributesForElementsInRect:方法
- (BOOL) shouldInvalidateLayoutForBoundsChange:(CGRect)newBound
{
    return YES;
}

UICollectionView是一個很強(qiáng)大的控件,還有很多強(qiáng)大的功能等著被挖掘, 希望在學(xué)習(xí)的道路上可以一起跟大牛的余香找點感覺 嘻嘻....

具體代碼點擊后面 點擊此處跳轉(zhuǎn)到github源碼

如果覺得不錯或者可以用到 請star一下
如果覺得還有不好的地方,請?zhí)岢鰧氋F的建議
在編程的道路上,如果愛,請深愛~

this article author : 會跳舞的獅子  如需轉(zhuǎn)載請注明原文地址 謝謝~!
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容