炫酷的UIcollectionlayout瀑布流

原文// github: https://github.com/jasnig
// : http://www.jianshu.com/p/b84f4dd96d0c

炫酷的UIcollectionlayout瀑布流_第1张图片
![850130ADDD4DEB1781C2BC446EEC84D1.jpg](http://upload-images.jianshu.io/upload_images/1402122-53722d56cd48ab9a.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

代码

protocol WaterFallLayoutDelegate: NSObjectProtocol {
    // 用来设置每一个cell的高度
    func heightForItemAtIndexPath(indexPath: IndexPath) -> CGFloat
}

class WaterFallLayout: UICollectionViewLayout {
    /// 共有多少列
    var numberOfColums = 0 {
        didSet {
            // 初始化为0
            for _ in 0.. UICollectionViewLayoutAttributes? {
        return layoutAttributes[indexPath.row]

    }
    
    // 必须重写这个方法来返回计算好的LayoutAttributes
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        // 返回计算好的layoutAttributes
        return layoutAttributes
    }
    
    // 返回collectionView的ContentSize -> 滚动范围
    //changed this -> override func collectionViewContentSize() -> CGSize to this->
    override var collectionViewContentSize:  CGSize {
        let maxY = maxYOfColums.max()!
        return CGSize(width: 0.0, height: maxY)
    }
    
    // 当collectionView的bounds(滚动, 或者frame变化)发生改变的时候就会调用这个方法
    override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
        // 旋转屏幕后刷新视图
        return newBounds.width != oldScreenWidth
        
    }
    // 计算所有的UICollectionViewLayoutAttributes
    func computeLayoutAttributes() -> [UICollectionViewLayoutAttributes] {
        //总共的item数量
        let totalNums = collectionView!.numberOfItems(inSection: 0)
        //每一个item的宽度 = (collectionview的宽度 - cell之间的间隙 默认为5.0 )/  列数
        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] = []
        //必须设置代理
        guard let unwapDelegate = delegate else {
            assert(false, "需要设置代理")
            return attributesArr
        }
        
        for index in 0..

简单使用

var cellCount = 40
    public lazy var cellHeight:[CGFloat] = { //changed private to public
        var arr:[CGFloat] = []
        for _ in 0.. CGFloat {
        return cellHeight[indexPath.row]
    }
}

你可能感兴趣的:(炫酷的UIcollectionlayout瀑布流)