自定义layout实现纵向滚动置顶效果

前景

公司项目内有个小效果,页面内有不同样式的分组,其中包含普通列表和瀑布流,切纵向滑动需要将组header置顶,这里的置顶有可能是两种view,一个是滑动到第几组之后有一个常驻置顶,以及之后每组内容的header置顶, 简单画了一个示意图
下图中,红色位置是sectionHeader,需要根据滑动过程中动态置顶,
绿色框内容是当滑动到位置后常驻置顶的
黄色框就是不同分组内的内容

image.png

下面直接上代码
PinCollectionLayout.swift

protocol PinCollectionLayoutDelegate: NSObjectProtocol {
    func pinCollectionLayout_scrollDidScroll(section: Int)
    
    func pinCollectionLayout_itemSize(at indexPath: IndexPath) -> CGSize?
    func pinCollectionLayout_horItemSpacing(at indexPath: IndexPath) -> CGFloat?
    func pinCollectionLayout_verItemSpacing(at indexPath: IndexPath) -> CGFloat?
    func pinCollectionLayout_sectionInset(at section: Int) -> UIEdgeInsets
    func pinCollectionLayout_column(at section: Int) -> Int
}

class PinCollectionLayout: UICollectionViewFlowLayout {
    var pinSection = 0
    var maxWidth = UIDevice.isIPad() ? Scale(560) : ScreenWidth
    private var left: CGFloat = 0
    weak var delegate: PinCollectionLayoutDelegate? = nil
    private var pinAttribute: UICollectionViewLayoutAttributes?
    private var results: [UICollectionViewLayoutAttributes] = []
    private var lastPinMaxBoundryY: CGFloat = 0
    private var lastPinMinBoundryY: CGFloat = 0
    private var sectionHeights: [[CGFloat]] = []
    private var sectionAttributes: [UICollectionViewLayoutAttributes?] = []
    //边界发生变化时是否重新布局(视图滚动的时候也会调用)
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        return true
    }
    
    
    override func prepare() {
        super.prepare()
        results.removeAll()
        let maxWidth = self.maxWidth > 0 ? self.maxWidth : (collectionView?.width ?? ScreenWidth)
        left = ((collectionView?.width ?? ScreenWidth) - maxWidth) / 2
        if let sections = collectionView?.numberOfSections {
            if sectionAttributes.isEmpty {
                sectionAttributes = Array.init(repeating: nil, count: sections)
            }
            sectionHeights = Array.init(repeating: [], count: sections)
            for i in 0..<sections {
                if let sectionInsets = self.delegate?.pinCollectionLayout_sectionInset(at: i) {
                    left = sectionInsets.left
                } else {
                    left = ((collectionView?.width ?? ScreenWidth) - maxWidth) / 2
                }
                let column = self.delegate?.pinCollectionLayout_column(at: i) ?? 1
                var top: CGFloat = 0
                if i > 0 {
                    top = sectionHeights[i-1].max() ?? 0
                    if let sectionInsets = self.delegate?.pinCollectionLayout_sectionInset(at: i - 1) {
                        top += sectionInsets.bottom
                    }
                }
                let indexPath = IndexPath.init(row: 0, section: i)
                if let att = super.layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath) {
                    top += att.frame.size.height
                    if let sectionInsets = self.delegate?.pinCollectionLayout_sectionInset(at: i) {
                        top += sectionInsets.top
                    }
                }
                sectionHeights[i] = Array.init(repeating: top, count: column)
                if let rows = collectionView?.numberOfItems(inSection: i) {
                    for j in 0..<rows {
                        let indexPath = IndexPath.init(row: j, section: i)
                        if let att = self.layoutAttributesForItem(at: indexPath) {
                            results.append(att)
                        }
                    }
                    if let att = self.layoutAttributesForSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, at: indexPath) {
                        results.append(att)
                    }
                }
            }
        }
    }
    
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let column = self.delegate?.pinCollectionLayout_column(at: indexPath.section) ?? 1
        let index = indexPath.row % column
        let cellSize = self.delegate?.pinCollectionLayout_itemSize(at: indexPath) ?? itemSize
        let maxWidth = self.maxWidth > 0 ? self.maxWidth : (collectionView?.width ?? ScreenWidth)
        var leftSpace: CGFloat = 0
        if let sectionInsets = self.delegate?.pinCollectionLayout_sectionInset(at: indexPath.section) {
            leftSpace = sectionInsets.left
        } else {
            leftSpace = ((collectionView?.width ?? ScreenWidth) - maxWidth) / 2
        }
        
        
        if left + cellSize.width > (leftSpace + maxWidth) {
            left = leftSpace
        }
       
        let spacing: CGFloat = self.delegate?.pinCollectionLayout_horItemSpacing(at: indexPath) ?? 0
        let attr = UICollectionViewLayoutAttributes(forCellWith: indexPath)
        attr.frame = CGRectMake(left, sectionHeights[indexPath.section][index], cellSize.width, cellSize.height)
        let verSpace: CGFloat = self.delegate?.pinCollectionLayout_verItemSpacing(at: indexPath) ?? 0
        sectionHeights[indexPath.section][index] += (cellSize.height + verSpace)
        if index < column - 1 {
            left += cellSize.width + spacing
        } else {
            left += cellSize.width
        }
        return attr
    }
    
    //所有元素的位置属性
    override func layoutAttributesForElements(in rect: CGRect)
        -> [UICollectionViewLayoutAttributes]? {
            return results
    }
    
    override var collectionViewContentSize: CGSize {
        let maxHeight = self.sectionHeights.last?.max() ?? 0
        return CGSizeMake(self.collectionView?.width ?? 0, maxHeight)
    }
    
    //补充视图的布局属性(这里处理实现粘性分组头,让分组头始终处于分组可视区域的顶部)
    override func layoutAttributesForSupplementaryView(ofKind elementKind: String,
                    at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        var layoutAttributes: UICollectionViewLayoutAttributes?
        if let att = self.sectionAttributes[indexPath.section] {
            layoutAttributes = att
        } else if let l = super.layoutAttributesForSupplementaryView(ofKind: elementKind, at: indexPath) {//先从父类获取补充视图的布局属性
            layoutAttributes = l
        }
        guard let layoutAttributes = layoutAttributes else { return nil }
        
       
        //如果不是头部视图则直接返回
        if elementKind != UICollectionView.elementKindSectionHeader {
            return layoutAttributes
        }
        
        //根据section索引,获取对应的边界范围
        guard let boundaries = boundaries(forSection: indexPath.section) else {
                return layoutAttributes
            }
        guard let collectionView = collectionView else {
            return layoutAttributes
        }
        
        self.sectionAttributes[indexPath.section] = layoutAttributes

        
        //保存视图内入垂直方向的偏移量
        let contentOffsetY = collectionView.contentOffset.y
        //补充视图的frame
        var frameForSupplementaryView = layoutAttributes.frame
        
        //计算分组头垂直方向的最大最小值
        let minimum = boundaries.minimum
        let maximum = boundaries.maximum - frameForSupplementaryView.height
        
        //如果内容区域的垂直偏移量小于分组头最小的位置,则将分组头置于其最小位置
        var pinOffset: CGFloat = 0
        if indexPath.section > pinSection, let pin = self.pinAttribute {
            pinOffset = pin.frame.size.height
        }
        if contentOffsetY < minimum - pinOffset {
            frameForSupplementaryView.origin.y = minimum
            lastPinMinBoundryY = minimum

        }
        //如果内容区域的垂直偏移量大于分组头最大的位置,则将分组头置于其最大位置
        else if contentOffsetY > maximum - pinOffset {
            frameForSupplementaryView.origin.y = maximum - pinOffset - 1
            lastPinMaxBoundryY = maximum + pinOffset

        }
        //如果都不满足,则说明内容区域的垂直便宜量落在分组头的边界范围内。
        //将分组头设置为内容偏移量,从而让分组头固定在集合视图的顶部
        else {
            frameForSupplementaryView.origin.y = contentOffsetY + pinOffset - 1
            self.delegate?.pinCollectionLayout_scrollDidScroll(section: indexPath.section)
        }
        
        if indexPath.section == pinSection {
            if contentOffsetY > frameForSupplementaryView.origin.y {
                frameForSupplementaryView.origin.y = contentOffsetY
            }
            self.pinAttribute = layoutAttributes
            self.pinAttribute?.zIndex = 1000 //将置顶sectionheader放到最上层视图
        }
        //更新布局属性并返回
        let maxWidth = self.maxWidth > 0 ? self.maxWidth : collectionView.width

        frameForSupplementaryView.origin.x = (collectionView.width - maxWidth) / 2
        frameForSupplementaryView.size.width = maxWidth
        layoutAttributes.frame = frameForSupplementaryView
        return layoutAttributes
    }
    
    //根据section索引,获取对应的边界范围(返回一个元组)
    func boundaries(forSection section: Int) -> (minimum: CGFloat, maximum: CGFloat)? {
        var min:CGFloat = 0
        if section > 0 {
            min = (sectionHeights[section - 1].max() ?? 0) - headerReferenceSize.height
        }
        let max: CGFloat = (sectionHeights[section].max() ?? 0) - headerReferenceSize.height
        //返回最终的边界值
        return (minimum: min, maximum: max)
    }
    

}


extension PinCollectionLayout {
    func scrollToSection(at section: Int, animated: Bool) {
        var offset: CGFloat = 0
        if section > 0, sectionHeights.count > section {
            offset = sectionHeights[section - 1].max() ?? 0
        }
        let indexPath = IndexPath.init(row: 0, section: section)
        offset -= ((pinAttribute?.frame.size.height ?? 0))
        self.collectionView?.setContentOffset(CGPoint.init(x: 0, y: offset + 1), animated: animated)
    }
}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,427评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,551评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,747评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,939评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,955评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,737评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,448评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,352评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,834评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,992评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,133评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,815评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,477评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,022评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,147评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,398评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,077评论 2 355

推荐阅读更多精彩内容