关于UICollectionView的头部悬浮(类似UITableView)

在iOS9之前系统是并不支持UICollectionView的头部视图悬浮的,因此需要自定义UICollectionViewFlowLayout去实现悬浮效果。


import UIKit

class CollectionViewFloatLayout: UICollectionViewFlowLayout {
    
    //边界发生变化时是否重新布局(视图滚动的时候也会调用)
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

        //获取到父类所返回的数组(里面放的是当前屏幕所能展示的item的结构信息),并转化成不可变数组
        guard var attributesArray = super.layoutAttributesForElements(in: rect) else { return nil }

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

        //遍历,得到一个当前屏幕中所有的section数组
        for layoutAttribute in attributesArray where (layoutAttribute.representedElementCategory == .cell) {
            noneHeaderSections.insert(layoutAttribute.indexPath.section)
        }

        /**
         遍历superArray,将当前屏幕中拥有的header的section从数组中移除,得到一个当前屏幕中没有header的section数组
         正常情况下,随着手指往上移,header脱离屏幕会被系统回收而cell尚在,也会触发该方法
         */
        for layoutAttribute in attributesArray where (layoutAttribute.representedElementKind == UICollectionView.elementKindSectionHeader) {
            noneHeaderSections.remove(layoutAttribute.indexPath.section)
        }

        for index in 0.. 0 {
                //cell有值,则获取第一个cell和最后一个cell的结构信息
                firstAttributes = self.layoutAttributesForItem(at: firstIndexPath)
                lastAttributes = self.layoutAttributesForItem(at: lastIndexPath)
            } else {
                //cell没值,就新建一个UICollectionViewLayoutAttributes
                firstAttributes = UICollectionViewLayoutAttributes()
                let attributeY = attributes.frame.maxY + self.sectionInset.top
                firstAttributes!.frame = CGRect(x: 0, y: attributeY, width: 0, height: 0)
                //因为只有一个cell,所以最后一个cell等于第一个cell
                lastAttributes = firstAttributes
            }

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

            //当前的滑动距离 + 因为导航栏产生的偏移量,默认为64(如果app需求不同,需自己设置)
            let offset = (self.collectionView?.contentOffset.y ?? 0)
            //第一个cell的y值 - 当前header的高度 - 可能存在的sectionInset的top
            var sectionInsets = UIEdgeInsets.zero
            //swiftlint:disable force_cast
            //swiftlint:disable line_length
            if let clv = self.collectionView, let delegate = clv.delegate, delegate is  UICollectionViewDelegateFlowLayout {
                sectionInsets = (delegate as! UICollectionViewDelegateFlowLayout).collectionView?(clv, layout: self, insetForSectionAt: attributes.indexPath.section) ?? UIEdgeInsets.zero
            }
            let headerY = firstAttributes!.frame.minY - rect.height - sectionInsets.top
            
            //哪个大取哪个,保证header悬停
            //针对当前header基本上都是offset更加大,针对下一个header则会是headerY大,各自处理
            let maxY = max(offset, headerY)

            /**
             最后一个cell的y值 + 最后一个cell的高度 + 可能存在的sectionInset的bottom - 当前header的高度
              当当前section的footer或者下一个section的header接触到当前header的底部,计算出的headerMissingY即为有效值
             */

            let headerMissingY = lastAttributes!.frame.maxY + self.sectionInset.top - rect.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 attributesArray

    }

}

上面也仅仅是实现了悬浮,但是其效果仍然不尽人意,在滑动的时候并不会在当前的section范围内一直停留。效果并不是很理想,因此如果是是在需要支持iOS9之前的版本也可以用该方法。

iOS9之后系统有提供相关的API来支持头部悬浮效果:

 let layout = UICollectionViewFlowLayout()
 layout.sectionHeadersPinToVisibleBounds = true

你可能感兴趣的:(关于UICollectionView的头部悬浮(类似UITableView))