MG--OC和Swift的瀑布流布局

作者: Mg明明就是你 | 来源:发表于2017-05-26 14:06 被阅读196次
    • 瀑布流(OC和Swift)

      • 算封装的比较好。提供接口,只需要成为MGWaterFlayout的代理,即可在外界设置那个cell的间距,collection View 的inset等进行UI界面的布局,非常方便。

      • 效果

    1.png
    2.png
    瀑布流.gif
    • github网址:

    OC源码查看

    Swift源码项目查看


    • OC

      • .h

    //  MGWaterflowLayout.h
    //  MGPuBuLiuDemo
    //  Created by ming on 16/6/9.
    //  Copyright © 2016年 ming. All rights reserved.
    
    #import <UIKit/UIKit.h>
    @class MGWaterflowLayout;
    
    #pragma mark - 协议
    @protocol MGWaterflowLayoutDelegate <NSObject>
    @optional
    - (CGFloat)waterflowLayout:(MGWaterflowLayout *)waterflowLayout heightForItemAtIndex:(NSIndexPath *)indexPath itemWidth:(CGFloat)itemWidth;
    
    @optional
    - (CGFloat)columnCountInWaterflowLayout:(MGWaterflowLayout *)waterflowLayout;
    - (CGFloat)columnMarginInWaterflowLayout:(MGWaterflowLayout *)waterflowLayout;
    - (CGFloat)rowMarginInWaterflowLayout:(MGWaterflowLayout *)waterflowLayout;
    - (UIEdgeInsets)edgeInsetsInWaterflowLayout:(MGWaterflowLayout *)waterflowLayout;
    - (CGSize)layoutCollectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)layout
      sizeForItemAtIndexPath:(NSIndexPath *)indexPath;
    @end
    
    
    
    #pragma mark - MGWaterflowLayout
    @interface MGWaterflowLayout : UICollectionViewFlowLayout
    /** 代理 */
    @property (nonatomic, weak) id<MGWaterflowLayoutDelegate> delegate;
    @end```
    
      - #.m
    
    

    // MGWaterflowLayout.m
    // MGPuBuLiuDemo
    // Created by ming on 16/6/9.
    // Copyright © 2016年 ming. All rights reserved.

    import "MGWaterflowLayout.h"

    /** 默认的列数 /
    static const NSInteger MGDefaultColumnCount = 3;
    /
    * 每一列之间的间距 /
    static const CGFloat MGDefaultColumnMargin = 10;
    /
    * 每一行之间的间距 /
    static const CGFloat MGDefaultRowMargin = 10;
    /
    * 边缘间距 */
    static const UIEdgeInsets MGDefaultEdgeInsets = {10, 10, 10, 10};

    @interface MGWaterflowLayout ()

    /** 存放所有cell的布局属性 /
    @property (nonatomic, strong) NSMutableArray attrsArray;
    /
    存放所有列的当前高度 */
    @property (nonatomic, strong) NSMutableArray *columnHeights;

    /** 每一行之间的间距 */

    • (CGFloat)rowMargin;
      /** 每一列之间的间距 */
    • (CGFloat)columnMargin;
      /** 列数 */
    • (NSInteger)columnCount;
      /** 边缘间距 */
    • (UIEdgeInsets)edgeInsets;

    @end

    @implementation MGWaterflowLayout

    pragma mark - 常见数据处理

    • (CGFloat)rowMargin
      {
      if ([self.delegate respondsToSelector:@selector(rowMarginInWaterflowLayout:)]) {
      return [self.delegate rowMarginInWaterflowLayout:self];
      } else {
      return MGDefaultRowMargin;
      }
      }

    • (CGFloat)columnMargin
      {
      if ([self.delegate respondsToSelector:@selector(columnMarginInWaterflowLayout:)]) {
      return [self.delegate columnMarginInWaterflowLayout:self];
      } else {
      return MGDefaultColumnMargin;
      }
      }

    • (NSInteger)columnCount
      {
      if ([self.delegate respondsToSelector:@selector(columnCountInWaterflowLayout:)]) {
      return [self.delegate columnCountInWaterflowLayout:self];
      } else {
      return MGDefaultColumnCount;
      }
      }

    • (UIEdgeInsets)edgeInsets
      {
      if ([self.delegate respondsToSelector:@selector(edgeInsetsInWaterflowLayout:)]) {
      return [self.delegate edgeInsetsInWaterflowLayout:self];
      } else {
      return MGDefaultEdgeInsets;
      }
      }

    pragma mark - 懒加载

    • (NSMutableArray *)columnHeights
      {
      if (!_columnHeights) {
      _columnHeights = [NSMutableArray array];
      }
      return _columnHeights;
      }

    • (NSMutableArray *)attrsArray
      {
      if (!_attrsArray) {
      _attrsArray = [NSMutableArray array];
      }
      return _attrsArray;
      }

    • (void)prepareLayout{
      [super prepareLayout];

    warning 删除以前保存的高度

    [self.columnHeights removeAllObjects];
    for (NSInteger i = 0; i < self.columnCount; i++) {
        [self.columnHeights addObject:@(self.edgeInsets.top)];
    }
    
    
    // 清除之前所有的布局属性
    [self.attrsArray removeAllObjects];
    // 1.获取cell的个数
    NSInteger count = [self.collectionView numberOfItemsInSection:0];
    
    
    // 清除之前所有的布局属性
    [self.attrsArray removeAllObjects];
    
    // 2.遍历cell,把每一个布局添加到数组
    for (NSInteger i = 0; i < count; i++) {
        // 创建位置
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
        // 获取indexPath位置cell对应的布局属性
        UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:indexPath];
        [self.attrsArray addObject:attrs];
    }
    

    }

    • (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
      // 创建布局属性
      UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];

      CGFloat x,y,w,h;

    // w = (self.collectionView.frame.size.width - [self edgeInsets].left - [self edgeInsets].right - ([self columnCount] - 1) * MGDefaultColumnMargin)/[self columnCount];
    w = (self.collectionView.frame.size.width - self.edgeInsets.left - self.edgeInsets.right - (self.columnCount - 1) * self.columnMargin) / self.columnCount;

    // 通过代理可以设置高度
    if ([self.delegate respondsToSelector:@selector(waterflowLayout:heightForItemAtIndex:itemWidth:)]) {
        h = [self.delegate waterflowLayout:self heightForItemAtIndex:indexPath itemWidth:w];
    }else{
        h = 70 + arc4random_uniform(100);
    }
    
    // 取得所有列中高度最短的列
    NSInteger minHeightColumn = [self minHeightColumn];
    

    // x = MGDefaultEdgeInsets.left + minHeightColumn * (w + MGDefaultColumnMargin);
    x = self.edgeInsets.left + minHeightColumn * (w + self.columnMargin);

    y = self.edgeInsets.top + [self.columnHeights[minHeightColumn] floatValue] + self.rowMargin;
    

    warning 更改最短的一列

    [self.columnHeights replaceObjectAtIndex:minHeightColumn withObject:@(y+h)];
    
    attrs.frame = CGRectMake(x, y, w, h);
    
    return attrs;
    

    }

    /**

    • 决定cell的排布
    • 第一次显示时会调用一次
    • 用力拖拽时也会调一次
      */
    • (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
      return self.attrsArray;
      }

    /// 返回collectionView的滚动范围

    • (CGSize)collectionViewContentSize{
      if (self.columnHeights.count == 0) {
      return CGSizeMake(0, 0);
      }

      // 获得最高的列
      NSInteger maxColum = [self maxHeightColumn];

      CGFloat height = [self.columnHeights[maxColum] floatValue] + MGDefaultEdgeInsets.bottom;
      CGFloat width = self.collectionView.frame.size.width;

      return CGSizeMake(width, height);
      }

    /// 取得所有列中高度最短的列

    • (NSInteger)minHeightColumn{
      // 找出columnHeights的最小值
      NSInteger minHeightColum = 0;
      CGFloat minColumHeight = [self.columnHeights[0] floatValue];

      for (NSInteger i = 1; i < self.columnHeights.count; i++) {
      CGFloat tempHeight = [self.columnHeights[i] floatValue];

        if (tempHeight < minColumHeight) {
            minHeightColum = i;
            minColumHeight = tempHeight;
        }
      

      }
      return minHeightColum;
      }

    /// 取得所有列中高度最高的列

    • (NSInteger)maxHeightColumn{
      // 找出columnHeights的最小值
      NSInteger maxHeightColumn = 0;
      CGFloat maxColumnHeight = [self.columnHeights[0] floatValue];

      for (NSInteger i = 1; i < self.columnHeights.count; i++) {
      CGFloat tempHeight = [self.columnHeights[i] floatValue];

        if (tempHeight > maxColumnHeight) {
            maxHeightColumn = i;
            maxColumnHeight = tempHeight;
        }
      

      }
      return maxHeightColumn;
      }

    ///**
    // * 在元素的Interactive Movement期间被调用
    // * 它带有target(目标元素)和先前的cell的indexPaths(索引地址)
    // */
    //- (UICollectionViewLayoutInvalidationContext *)invalidationContextForInteractivelyMovingItems:(NSArray<NSIndexPath *> *)targetIndexPaths withTargetPosition:(CGPoint)targetPosition previousIndexPaths:(NSArray<NSIndexPath *> )previousIndexPaths previousPosition:(CGPoint)previousPosition{
    // UICollectionViewLayoutInvalidationContext context = [super invalidationContextForInteractivelyMovingItems:targetIndexPaths withTargetPosition:targetPosition previousIndexPaths:previousIndexPaths previousPosition:previousPosition];
    // [self.collectionView moveItemAtIndexPath:previousIndexPaths[0] toIndexPath:targetIndexPaths[0]];
    //
    // [self.collectionView reloadData];
    // return context;
    //}
    //
    ///

    // * 这个与上一个函数类似,但它只在Interactive Movement结束后才调用
    // * 它带有target(目标元素)和先前的cell的indexPaths(索引地址)
    // */
    //- (UICollectionViewLayoutInvalidationContext *)invalidationContextForEndingInteractiveMovementOfItemsToFinalIndexPaths:(NSArray<NSIndexPath *> *)indexPaths previousIndexPaths:(NSArray<NSIndexPath *> *)previousIndexPaths movementCancelled:(BOOL)movementCancelled{
    // UICollectionViewLayoutInvalidationContext *context = [super invalidationContextForEndingInteractiveMovementOfItemsToFinalIndexPaths:indexPaths previousIndexPaths:previousIndexPaths movementCancelled:movementCancelled];
    // [self.collectionView moveItemAtIndexPath:previousIndexPaths[0] toIndexPath:indexPaths[0]];
    // return context;
    //}

    @end```




    • Swift

    //  MGWaterFlowLayout.swift
    //  MGDS_Swift
    //  Created by i-Techsys.com on 17/1/21.
    //  Copyright © 2017年 i-Techsys. All rights reserved.
    
    import UIKit
    
    // MARK: - 协议
    @objc
    protocol MGWaterFlowLayoutDelegate: NSObjectProtocol {
        @objc optional func waterflowLayout(waterflowLayout: MGWaterFlowLayout,heightForItemAtIndex indexPath: IndexPath,itemWidth: CGFloat) -> CGFloat
        @objc optional  func columnCountInWaterflowLayout(waterflowLayout: MGWaterFlowLayout) -> Int
        @objc optional  func columnMarginInWaterflowLayout(waterflowLayout: MGWaterFlowLayout) -> CGFloat
        @objc optional  func rowMarginInWaterflowLayout(waterflowLayout: MGWaterFlowLayout) -> CGFloat
        @objc optional  func edgeInsetsInWaterflowLayout(waterflowLayout: MGWaterFlowLayout) -> UIEdgeInsets  
        @objc optional func layoutCollectionView(collectionView: UICollectionView,layout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: IndexPath)
    }
    
    
    // MARK: - 默认参数
    /** 默认的列数 */
    private let MGDefaultColumnCount: Int = 3
    /** 每一列之间的间距 */
    private let MGDefaultColumnMargin: CGFloat = 10
    /** 每一行之间的间距 */
    private let MGDefaultRowMargin: CGFloat = 10
    /** 边缘间距 */
    private let MGDefaultEdgeInsets: UIEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    
    
    class MGWaterFlowLayout: UICollectionViewFlowLayout {
        // MARK: - 自定义属性
        /** 存放所有cell的布局属性 */
        fileprivate var attrsArray = [UICollectionViewLayoutAttributes]()
        /** 存放所有列的当前高度 */
        fileprivate var columnHeights: [CGFloat] = [CGFloat]()
        /** MGWaterFlowLayout的代理 */
        weak var delegate: MGWaterFlowLayoutDelegate?
    }
    
    // MARK: - 边距和距离等
    extension MGWaterFlowLayout {
        func rowMargin() -> CGFloat {
            if (self.delegate?.responds(to: #selector(MGWaterFlowLayoutDelegate.rowMarginInWaterflowLayout(waterflowLayout:))))! {
                return (delegate?.rowMarginInWaterflowLayout!(waterflowLayout: self))!
            }else {
                return MGDefaultRowMargin
            }
        }
        
        func columnMargin() -> CGFloat {
            if (self.delegate?.responds(to: #selector(MGWaterFlowLayoutDelegate.columnMarginInWaterflowLayout(waterflowLayout:))))! {
                return (delegate?.columnMarginInWaterflowLayout!(waterflowLayout: self))!
            }else {
                return MGDefaultColumnMargin
            }
        }
        
        func columnCount() -> Int {
            if (self.delegate?.responds(to: #selector(MGWaterFlowLayoutDelegate.columnCountInWaterflowLayout(waterflowLayout:))))! {
                return (delegate?.columnCountInWaterflowLayout!(waterflowLayout: self))!
            }else {
                return MGDefaultColumnCount
            }
        }
        
        func edgeInsets() -> UIEdgeInsets {
            if (self.delegate?.responds(to: #selector(MGWaterFlowLayoutDelegate.edgeInsetsInWaterflowLayout(waterflowLayout:))))! {
                return (delegate?.edgeInsetsInWaterflowLayout!(waterflowLayout: self))!
            }else {
                return MGDefaultEdgeInsets
            }
        }
    }
    
    // MARK: - 系统方法
    extension MGWaterFlowLayout {
        override func prepare() {
            super.prepare()
            columnHeights.removeAll()
            
            for _ in 0..<self.columnCount() {
                self.columnHeights.append(self.edgeInsets().top)
            }
            
            // 清除之前所有的布局属性
            attrsArray.removeAll()
            
            // 1.获取cell的个数
           let count = (collectionView?.numberOfItems(inSection: 0))! as Int
            
            // 2.遍历cell,把每一个布局添加到数组
            for i in 0..<count {
                let indexPath = IndexPath(item: i, section: 0)
                let attrs = self.layoutAttributesForItem(at: indexPath)
                attrsArray.append(attrs!)
            }
        }
        
        override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
            super.layoutAttributesForItem(at: indexPath)
            // 创建布局属性
            let attrs = UICollectionViewLayoutAttributes(forCellWith: indexPath)
            
            var x,y,w,h :CGFloat
            
            w = (self.collectionView!.frame.size.width - self.edgeInsets().left - self.edgeInsets().right - (CGFloat(self.columnCount()-1) * self.columnMargin())) / CGFloat(self.columnCount())
            
            // 通过代理可以设置高度
            if (self.delegate?.responds(to: #selector(MGWaterFlowLayoutDelegate.waterflowLayout(waterflowLayout:heightForItemAtIndex:itemWidth:))))! {
                h = self.delegate!.waterflowLayout!(waterflowLayout: self, heightForItemAtIndex: indexPath, itemWidth: w)
            }else {
                h = CGFloat(70) + CGFloat(arc4random_uniform(100))
            }
            
            
            // 取得所有列中高度最短的列
            let minHeightColumn = self.minHeightColumn()
            
            x = self.edgeInsets().left + CGFloat(minHeightColumn) * (w + self.columnMargin());
            
            y = self.edgeInsets().top + self.columnHeights[minHeightColumn] + self.rowMargin()
            
            // #warning 更改最短的一列
            self.columnHeights[minHeightColumn] = y + h
            
            attrs.frame = CGRect(x: x, y: y, width: w, height: h)
            
            return attrs;
        }
        
        /**
         * 决定cell的排布
         * 第一次显示时会调用一次
         * 用力拖拽时也会调一次
         */
        override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
            super.layoutAttributesForElements(in: rect)
            return self.attrsArray
        }
        
        /// 返回collectionView的滚动范围
        override var collectionViewContentSize: CGSize {
            let _ = super.collectionViewContentSize
            if (self.columnHeights.count == 0) {
                return CGSize.zero
            }
            
            // 获得最高的列
            let maxColum = self.maxHeightColumn()
            
            let height: CGFloat = self.columnHeights[maxColum] + MGDefaultEdgeInsets.bottom;
            let width: CGFloat = self.collectionView!.frame.size.width;
            
            return CGSize(width: width, height: height)
        }
    }
    
    // MARK: - 自定义方法
    extension MGWaterFlowLayout {
        /// 取得所有列中高度最短的列
        fileprivate func minHeightColumn() -> Int {
            // 找出columnHeights的最小值
            var minHeightColum: Int = 0
            var minColumHeight: CGFloat = self.columnHeights[0]
            
            for i in 1..<columnHeights.count {
                let tempHeight:CGFloat = self.columnHeights[i]
            
                if (tempHeight < minColumHeight) {
                    minHeightColum = i;
                    minColumHeight = tempHeight;
                }
            }
            return minHeightColum
        }
        
        /// 取得所有列中高度最高的列
       fileprivate func maxHeightColumn() -> Int {
            // 找出columnHeights的最高值
            var maxHeightColumn: Int = 0
            var maxColumnHeight: CGFloat = self.columnHeights[0]
            
            for i in 1..<columnHeights.count {
                let tempHeight:CGFloat = self.columnHeights[i]
                
                if (tempHeight < maxColumnHeight) {
                    maxHeightColumn = i
                    maxColumnHeight = tempHeight
                }
            }
            return maxHeightColumn
        }
    }```
    
    ***
    >- #轻轻点击,关注我简书
    ##[轻轻点击,关注我简书](http://www.jianshu.com/u/57b58a39b70e)
    ##[轻轻点击,关注我微博](http://weibo.com/2778589865/profile?rightmod=1&wvr=6&mod=personinfo)
    ##[浏览我的GitHub](https://github.com/LYM-mg)
    
    ***
    >- #扫一扫,关注我
    ![扫一扫,关注我.jpg](http:https://img.haomeiwen.com/i1429890/718e413200b2b739.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

    相关文章

      网友评论

        本文标题:MG--OC和Swift的瀑布流布局

        本文链接:https://www.haomeiwen.com/subject/vhytfxtx.html