多组(section)瀑布流 swift5

可以直接复制使用

Simulator Screen Shot - iPhone 11 Pro Max - 2019-11-07 at 11.36.50.png

import UIKit

@objc protocol LauViewFlowLayoutDelegate : NSObjectProtocol {
    // 返回高度
    func LausetCellNormalSize(in collectionView:UICollectionView) -> CGSize
    // 返回行数
    @objc optional func LauColumnCountInWaterFlowLayout(in collectionView: UICollectionView) -> Int
    // 返回列间距
    @objc optional func LauDefaultColumnMarginInWaterFlowLayout(in collectionView: UICollectionView) -> CGFloat
    // 返回行间距
    @objc optional func LauRowMarginInWaterFlowLayout(in collectionView: UICollectionView) -> CGFloat
    //内边距
    @objc optional func LauEdgeInsetsInWaterFlowLayout(in collectionView: UICollectionView) -> UIEdgeInsets
    //组数
    @objc optional func LauNumberOfSections(in collectionView: UICollectionView) -> Int
    //特殊的cell在哪个Indexpath
    @objc optional func LauSpecialCellIndexpath(in collectionView:UICollectionView) -> IndexPath
    //特殊的cell的对应size
    @objc optional func LauSpecialCellSize(in collectionView:UICollectionView, numberOfItemsInSection section: Int) -> CGSize

}

class LauLayout: UICollectionViewLayout {
    weak var delegate:LauViewFlowLayoutDelegate?
    
    /** 默认列数 */

    private var DefaultColumnCount : Int = 5
    private var DefaultSize:CGSize = CGSize.init(width: 50, height: 50)
    private var SpecialSize:CGSize = CGSize.init(width: 50, height: 50)
    private var SpecialIndex:IndexPath = IndexPath.init(item: 0, section: 0) //这个后续再支持
    // 记录 collectionView 的 content 可滑动的范围
    fileprivate var contentScope: CGFloat = 0
    /** 每一列之间的间距 垂直 */
    private var DefaultColumnMargin : CGFloat = 0.0
    /** 每一行之间的间距 水平方向 */
    private var DefaultRowMargin : CGFloat = 0.0
    /** 边缘间距 */
    private var DefaultEdgeInsets : UIEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    private var LastSectionMaxHeight:CGFloat = 0
    //懒加载
    //存放所有cell的布局属性
    fileprivate lazy var attrsArrayArray = [UICollectionViewLayoutAttributes]()
    //存放所有列的当前高度
    fileprivate lazy var columnHeightsAry = [CGFloat]()
    //    fileprivate lazy var SectionItemHeightArray: [CGFloat] = []
    
    //第一步 :初始化
    override func prepare() {
        super.prepare()
        //清除高度
        columnHeightsAry.removeAll()
        self.contentScope = 0.0
        self.getconfigData()
        for _ in 0 ..< DefaultColumnCount {
            columnHeightsAry.append(DefaultEdgeInsets.top)
        }
        
        //清除所有的布局属性
        attrsArrayArray.removeAll()
        
        let sections : Int = (self.collectionView?.numberOfSections)!
        for num in 0 ..< sections {
            let count : Int = (self.collectionView?.numberOfItems(inSection: num))!//获取分区0有多少个item
            if self.delegate != nil && self.delegate?.responds(to: #selector(LauViewFlowLayoutDelegate.LauSpecialCellSize(in:numberOfItemsInSection:))) ?? false {
                if let contentView = self.collectionView {
                    self.SpecialSize =  self.delegate?.LauSpecialCellSize?(in: contentView, numberOfItemsInSection: num) ?? CGSize.init(width: self.DefaultSize.width, height: self.DefaultSize.height)
                    
                }
                
            }
            for i in 0 ..< count {
                let indexpath : NSIndexPath = NSIndexPath.init(item: i, section: num)
                let attrsArray = self.layoutAttributesForItem(at: indexpath as IndexPath)!
                attrsArrayArray.append(attrsArray)
            }
            let (_, maximumInteritemHeight) = maximumInteritemForSection(heightArray: columnHeightsAry)
            self.LastSectionMaxHeight = maximumInteritemHeight
            columnHeightsAry.removeAll()
            for _ in 0 ..< DefaultColumnCount {
                columnHeightsAry.append(DefaultEdgeInsets.top)
            }
        }
    }
    
    /**
     * 第二步 :返回indexPath位置cell对应的布局属性
     */
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        let attrsArray = UICollectionViewLayoutAttributes.init(forCellWith: indexPath)
        let _ItemWidth = DefaultSize.width
        var _ItemHeight = DefaultSize.height
        
        if self.SpecialSize.height != DefaultSize.height {
            if let nums = self.collectionView?.numberOfItems(inSection: indexPath.section){
                let mutiple = SpecialSize.height / DefaultSize.height
                if indexPath.row % nums == 0 {
                    _ItemHeight = SpecialSize.height + DefaultRowMargin * mutiple
                }else{
                    _ItemHeight = DefaultSize.height
                }
            }else{
                _ItemHeight = DefaultSize.height
            }
        }else{
            _ItemHeight = DefaultSize.height
        }
        
        

        let (minimumInteritemNumber, minimumInteritemHeight) = minimumInteritemForSection(heightArray: columnHeightsAry)
        let itemX = DefaultEdgeInsets.left + CGFloat(minimumInteritemNumber) * (_ItemWidth + DefaultColumnMargin)
        var itemY = minimumInteritemHeight
        let (_, maximumInteritemHeight) = maximumInteritemForSection(heightArray: columnHeightsAry)
        if indexPath.item < self.DefaultColumnCount {
            itemY = itemY + self.DefaultEdgeInsets.top + LastSectionMaxHeight
        }

        attrsArray.frame = CGRect(x: itemX, y: itemY, width: _ItemWidth, height: CGFloat(_ItemHeight))
        columnHeightsAry[minimumInteritemNumber] = attrsArray.frame.maxY
        if contentScope < maximumInteritemHeight {
            self.contentScope = maximumInteritemHeight
            self.contentScope = contentScope + DefaultEdgeInsets.bottom
        }
        return attrsArray
    }
    
    //第三步 :重写  返回所有列的高度
    override var collectionViewContentSize: CGSize {
        return CGSize.init(width: 0, height: self.contentScope + DefaultEdgeInsets.bottom)
    }
    
    //第四步 :返回collection的item的frame
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {

        return attrsArrayArray
    }
    
    private func getconfigData()  {
        guard let contentView = self.collectionView else { return }
        if self.delegate != nil && (self.delegate?.responds(to: #selector(LauViewFlowLayoutDelegate.LausetCellNormalSize(in:))) ?? false) {
            self.DefaultSize = self.delegate?.LausetCellNormalSize(in: contentView) ?? CGSize.init(width: 50, height: 50)
        }
        if self.delegate != nil && (self.delegate?.responds(to: #selector(LauViewFlowLayoutDelegate.LauRowMarginInWaterFlowLayout(in:))) ?? false){
            self.DefaultColumnCount = self.delegate?.LauColumnCountInWaterFlowLayout?(in: contentView) ?? 0
        }
        if self.delegate != nil && (self.delegate?.responds(to: #selector(LauViewFlowLayoutDelegate.LauDefaultColumnMarginInWaterFlowLayout(in:))) ?? false) {
            self.DefaultRowMargin = self.delegate?.LauDefaultColumnMarginInWaterFlowLayout?(in: contentView) ?? 0
        }
        if self.delegate != nil && (self.delegate?.responds(to: #selector(LauViewFlowLayoutDelegate.LauRowMarginInWaterFlowLayout(in:))) ?? false) {
            self.DefaultRowMargin = self.delegate?.LauRowMarginInWaterFlowLayout?(in: contentView) ?? 0
        }
        
        if self.delegate != nil && (self.delegate?.responds(to: #selector(LauViewFlowLayoutDelegate.LauEdgeInsetsInWaterFlowLayout(in:))) ?? false) {
            self.DefaultEdgeInsets = self.delegate?.LauEdgeInsetsInWaterFlowLayout?(in: contentView) ?? UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
        }
        if self.delegate != nil && (self.delegate?.responds(to: #selector(LauViewFlowLayoutDelegate.LauSpecialCellIndexpath(in:))) ?? false ) {
            self.SpecialIndex = self.delegate?.LauSpecialCellIndexpath?(in: contentView) ?? IndexPath.init(item: 0, section: 0)
        }
    }
    
    /*
     *  竖向布局: 计算高度最大的是哪一列                 / 横向布局:计算宽度最大的是哪一行
     *
     *  @param  heightArray: 缓存 section 高度的数组  / 缓存 section 宽度的数组
     *  return  返回最大列的列号和高度值                / 返回最大行的行号和宽度值
     */
    fileprivate func maximumInteritemForSection(heightArray: [CGFloat]) -> (Int, CGFloat) {
        if heightArray.count <= 0 {
            return (0, 0.0)
        }
        // 默认第0列的高度最小
        var maximumInteritemNumber = 0
        // 从缓存高度数组中取出第一个元素,作为最小的那一列的高度
        var maximumInteritemHeight = heightArray[0]
        // 遍历数组,查找出最小的列号和最小列的高度值
        for i in 1..<heightArray.count {
            let tempMaximumInteritemHeight = heightArray[i]
            if maximumInteritemHeight < tempMaximumInteritemHeight {
                maximumInteritemHeight = tempMaximumInteritemHeight
                maximumInteritemNumber = i
            }
        }
        return (maximumInteritemNumber, maximumInteritemHeight)
    }
    /*
     *  竖向布局: 计算高度最小的是哪一列                 / 横向布局:计算宽度最小的是哪一行
     *
     *  @param  heightArray: 缓存 section 高度的数组  / 缓存 section 宽度的数组
     *  return  返回最小列的列号和高度值                / 返回最小行的行号和高度值
     */
    fileprivate func minimumInteritemForSection(heightArray: [CGFloat]) -> (Int, CGFloat) {
        if heightArray.count <= 0 {
            return (0, 0.0)
        }
        // 默认第0列的高度最小
        var minimumInteritemNumber = 0
        // 从缓存高度数组中取出第一个元素,作为最小的那一列的高度
        var minimumInteritemHeight = heightArray[0]
        // 遍历数组,查找出最小的列号和最小列的高度值
        for i in 1..<heightArray.count {
            let tempMinimumInteritemHeight = heightArray[i]
            if minimumInteritemHeight > tempMinimumInteritemHeight {
                minimumInteritemHeight = tempMinimumInteritemHeight
                minimumInteritemNumber = i
            }
        }
        return (minimumInteritemNumber, minimumInteritemHeight)
    }
    
}

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