炫酷的UIcollectionlayout瀑布流

原文// github: https://github.com/jasnig
// 簡(jiǎn)書: http://www.lxweimin.com/p/b84f4dd96d0c

![850130ADDD4DEB1781C2BC446EEC84D1.jpg](http://upload-images.jianshu.io/upload_images/1402122-53722d56cd48ab9a.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

代碼

protocol WaterFallLayoutDelegate: NSObjectProtocol {
    // 用來(lái)設(shè)置每一個(gè)cell的高度
    func heightForItemAtIndexPath(indexPath: IndexPath) -> CGFloat
}

class WaterFallLayout: UICollectionViewLayout {
    /// 共有多少列
    var numberOfColums = 0 {
        didSet {
            // 初始化為0
            for _ in 0..<numberOfColums {
                maxYOfColums.append(0)
            }
        }
    }
    /// cell之間的間隙 默認(rèn)為5.0
    var itemSpace: CGFloat = 5.0
    
    weak var delegate: WaterFallLayoutDelegate?
    // 當(dāng)item比較少(幾百個(gè))的時(shí)候建議緩存
    // 當(dāng)有成千個(gè)item的時(shí)候建議其他方式計(jì)算
    private var layoutAttributes: [UICollectionViewLayoutAttributes] = []
    // 初始都設(shè)置為0
    private var maxYOfColums: [CGFloat] = []
    /// 用于記錄之前屏幕的寬度 便于在旋轉(zhuǎn)的時(shí)候刷新視圖
    private var oldScreenWidth: CGFloat = 0.0
    

    // 在這個(gè)方法里面計(jì)算好各個(gè)cell的LayoutAttributes 對(duì)于瀑布流布局, 只需要更改LayoutAttributes.frame即可
    // 在每次collectionView的data(init delete insert reload)變化的時(shí)候都會(huì)調(diào)用這個(gè)方法準(zhǔn)備布局
    override func prepare() {
        super.prepare()
        layoutAttributes = computeLayoutAttributes()
        // 設(shè)置為當(dāng)前屏幕的寬度
        oldScreenWidth = UIScreen.main.bounds.width //deleted ()
    }
    
    // Apple建議要重寫這個(gè)方法, 因?yàn)槟承┣闆r下(delete insert...)系統(tǒng)可能需要調(diào)用這個(gè)方法來(lái)布局
    
    override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
        return layoutAttributes[indexPath.row]

    }
    
    // 必須重寫這個(gè)方法來(lái)返回計(jì)算好的LayoutAttributes
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        // 返回計(jì)算好的layoutAttributes
        return layoutAttributes
    }
    
    // 返回collectionView的ContentSize -> 滾動(dòng)范圍
    //changed this -> override func collectionViewContentSize() -> CGSize to this->
    override var collectionViewContentSize:  CGSize {
        let maxY = maxYOfColums.max()!
        return CGSize(width: 0.0, height: maxY)
    }
    
    // 當(dāng)collectionView的bounds(滾動(dòng), 或者frame變化)發(fā)生改變的時(shí)候就會(huì)調(diào)用這個(gè)方法
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        // 旋轉(zhuǎn)屏幕后刷新視圖
        return newBounds.width != oldScreenWidth
        
    }
    // 計(jì)算所有的UICollectionViewLayoutAttributes
    func computeLayoutAttributes() -> [UICollectionViewLayoutAttributes] {
        //總共的item數(shù)量
        let totalNums = collectionView!.numberOfItems(inSection: 0)
        //每一個(gè)item的寬度 = (collectionview的寬度 - cell之間的間隙 默認(rèn)為5.0 )/  列數(shù)
        let width = (collectionView!.bounds.width - itemSpace * CGFloat(numberOfColums + 1)) / CGFloat(numberOfColums)
        
        var x: CGFloat
        var y: CGFloat
        var height: CGFloat
        var currentColum: Int
        var indexPath: IndexPath
        var attributesArr: [UICollectionViewLayoutAttributes] = []
        //必須設(shè)置代理
        guard let unwapDelegate = delegate else {
            assert(false, "需要設(shè)置代理")
            return attributesArr
        }
        
        for index in 0..<numberOfColums {
            self.maxYOfColums[index] = 0
        }
        for currentIndex in 0..<totalNums {
            indexPath = IndexPath(item: currentIndex, section: 0)
            
            height = unwapDelegate.heightForItemAtIndexPath(indexPath: indexPath)
            
            if currentIndex < numberOfColums {// 第一行直接添加到當(dāng)前的列
                currentColum = currentIndex
                
            } else {// 其他行添加到最短的那一列
                // 這里使用!會(huì)得到期望的值
                let minMaxY = maxYOfColums.min()!
                currentColum = maxYOfColums.index(of: minMaxY)!
            }
            //            currentColum = currentIndex % numberOfColums
            x = itemSpace + CGFloat(currentColum) * (width + itemSpace)
            // 每個(gè)cell的y
            y = itemSpace + maxYOfColums[currentColum]
            // 記錄每一列的最后一個(gè)cell的最大Y
            maxYOfColums[currentColum] = y + height
            
            let attributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            // 設(shè)置用于瀑布流效果的attributes的frame
            attributes.frame = CGRect(x: x, y: y, width: width, height: height)
            
            attributesArr.append(attributes)
        }
        return attributesArr
        
    }
}

簡(jiǎn)單使用

var cellCount = 40
    public lazy var cellHeight:[CGFloat] = { //changed private to public
        var arr:[CGFloat] = []
        for _ in 0..<self.cellCount {
            arr.append(CGFloat(arc4random() % 150 + 40))
        }
        return arr
    }()

 func setWaterFallLayout() {
        let layout = WaterFallLayout()
        layout.delegate = self
        layout.numberOfColums = 2
        collectionView?.collectionViewLayout = layout
        
    }
extension ViewController: WaterFallLayoutDelegate {
    func heightForItemAtIndexPath(indexPath: IndexPath) -> CGFloat {
        return cellHeight[indexPath.row]
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容

  • Android 自定義View的各種姿勢(shì)1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,595評(píng)論 25 708
  • afinalAfinal是一個(gè)android的ioc,orm框架 https://github.com/yangf...
    passiontim閱讀 15,569評(píng)論 2 45
  • 是誰(shuí) 灑下一地的金黃 落下一地的滄涼 吹來(lái)一縷縷憂傷 留下一陣陣彷徨 楓葉 墜入紅塵醉了一地的殤 千思萬(wàn)縷深深埋藏土壤
    鼓起勇氣走下去閱讀 179評(píng)論 0 1
  • 我對(duì)鞋子的執(zhí)念,來(lái)自于小時(shí)候。 那時(shí)生活水平一般,在買不了新衣服的情況下,最喜歡去表姐的房間里“掃蕩”。有次,表姐...
    定投盒子閱讀 944評(píng)論 12 18