美文网首页
UIKit_UICollectionView瀑布流,水平流水布局

UIKit_UICollectionView瀑布流,水平流水布局

作者: 陈胜华 | 来源:发表于2016-08-11 14:50 被阅读743次

    再次声明,仅当记录笔记用


    不规则布局的流水布局

    • 高度一致,则规则布局
    • 高度不一致,则瀑布流布局
    不设置任何属性 打开rowHeight属性,则规则
    //初始化
    - (void)initCollectinView {
        _myWaterView = ({  
            //布局规则,文件在下面
            DFWaterFlowLayout *flowLayout = [[DFWaterFlowLayout alloc]init];
            //打开这属性则规则
            //flowLayout.rowHeight = ([UIScreen mainScreen].bounds.size.width-40)/3.0;
    
            UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0,
                                                                                                 0,
                                                                                                 CGRectGetWidth(self.view.frame),
                                                                                                 CGRectGetHeight(self.view.frame))
                                                                 collectionViewLayout:flowLayout];
            collectionView.backgroundColor = [UIColor redColor];
            collectionView.dataSource = self;
            collectionView.delegate   = self;
            [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:collectionCellID3];
            [self.view addSubview:collectionView];
            collectionView;
        });
    }
    - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
      return 100;
    }
    
    //返回每一个 item 的 cell
    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
      UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionCellID3 forIndexPath:indexPath];
      cell.backgroundColor = [UIColor yellowColor];
      return cell;
    }
    
    - (CGFloat)waterFlowLayout:(DFWaterFlowLayout *)waterFlowLayout indexPath:(NSIndexPath *)indexPath width:(CGFloat)width {
        return 100;
    }
    

    DFWaterFlowLayout(瀑布流布局类)

    //.h文件,继承UICollectionViewLayout
    
    @class DFWaterFlowLayout;
    @protocol DFWaterFlowLayoutDelegate <NSObject>
    @required
    /*!
     *  @brief 每个Item的高度(传入高度一至,则规则;不规则就瀑布流)
     *
     *  @param waterFlowLayout waterFlowLayout对象
     *  @param indexPath       indexPath
     *  @param width           width
     *
     *  @return 高度
     */
    - (CGFloat)waterFlowLayout:(DFWaterFlowLayout *)waterFlowLayout indexPath:(NSIndexPath *)indexPath width:(CGFloat)width;
    
    @end
    
    /*!
     *  @brief 不规则布局的流水布局
     */
    @interface DFWaterFlowLayout : UICollectionViewLayout
    
    /*!
     瀑布流的每排个数(默认3)
     */
    @property (nonatomic,assign) NSInteger maxColumns;
    /*!
     瀑布流竖直方向的间距(上下间距,默认10)
     */
    @property (nonatomic,assign) CGFloat verticalMargin;
    /*!
     瀑布流水平方向的间距(左右间距,默认10)
     */
    @property (nonatomic,assign) CGFloat horzontalMargin;
    /*!
     瀑布流Cell整体偏移量(相对UICollectionView容器的偏移量)
     */
    @property (nonatomic,assign) UIEdgeInsets inserts;
    /*!
     瀑布流高度Item高度(如果实现代理,则失效)
     */
    @property (nonatomic,assign) CGFloat rowHeight;
    /*!
     设置代理,界获取高度(不实现代理方法,则每个Item的高度随机)
     */
    @property (nonatomic,  weak) id<DFWaterFlowLayoutDelegate> delegate;
    
    @end
    
    //.m实现文件
    @interface DFWaterFlowLayout () {
        //水平间距
        CGFloat _horizontalMargin ;
        //竖直间距
        CGFloat _verticalMargin ;
        //最大的列数
        NSInteger _maxColumns ;
        //每个item的四边距
        UIEdgeInsets _insets;
    }
    //保存每一列的高度
    @property (strong, nonatomic) NSMutableArray *perColumnMaxHeights;
    //保存所有元素的相关属性
    @property (strong, nonatomic) NSMutableArray<UICollectionViewLayoutAttributes*> *layoutAtts;
    
    @end
    
    @implementation DFWaterFlowLayout
    
    - (instancetype)init {
        if (self = [super init]) {
            _maxColumns = 3;
            _horizontalMargin = 10;
            _verticalMargin = 10;
            _insets = UIEdgeInsetsMake(0, 10, 0, 10);
        }
        return self;
    }
    
    - (NSMutableArray *)layoutAtts{
        if (!_layoutAtts) {
            _layoutAtts = [NSMutableArray array];
        }
        return _layoutAtts;
    }
    
    - (NSMutableArray *)perColumnMaxHeights{
        if (!_perColumnMaxHeights) {
            _perColumnMaxHeights = [NSMutableArray array];
        }
        return _perColumnMaxHeights;
    }
    
    // 因为在 “layoutAttributesForElementsInRect”可能调用多次,计算多次, 而导致每次的随机数,都不一样, 而造成覆盖现象
    // 所以在 预布局中处理, 可以只计算一次
    - (void)prepareLayout
    {
        [self.perColumnMaxHeights removeAllObjects];
        [self.layoutAtts removeAllObjects];
        
        NSInteger count = [self.collectionView numberOfItemsInSection:0];
        //初始化数组高度,因为第一行,不需要按照高度大小添加
        for (int i = 0; i < _maxColumns; i ++) {
            [self.perColumnMaxHeights addObject:@(_insets.top)];
        }
        
        CGFloat W = (self.collectionView.frame.size.width - _insets.left - _insets.right - (_maxColumns - 1) * _horizontalMargin ) / _maxColumns;
        CGFloat H ;
        CGFloat X,Y;
        
        for (int i = 0; i < count; i++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
            UICollectionViewLayoutAttributes *layoutAtt = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
            
            // 求出高度最小的列, 计算出 Y值
            Y = [self.perColumnMaxHeights[[self minColumn]] floatValue]+ _verticalMargin;
            // 计算出 X 值
            X = _insets.left +[self minColumn] * (W + _horizontalMargin) ;
            // 通过代理计算出 高度
            if ([self.delegate respondsToSelector:@selector(waterFlowLayout:indexPath:width:)]) {
                H = [self.delegate waterFlowLayout:self indexPath:indexPath width:W];
            } else if (_rowHeight > 0){
                H = _rowHeight;
            } else {
                H = 70 + arc4random_uniform(100);
            }
            // 将新算出来的高度,替换 原来数组中对应的最低高度位置
            [self.perColumnMaxHeights replaceObjectAtIndex:[self minColumn] withObject:@(Y + H)];
            
            layoutAtt.frame = CGRectMake(X, Y, W, H);
            
            [self.layoutAtts addObject:layoutAtt];
        }
    }
    
    - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect{
        
        return self.layoutAtts;
    }
    
    // 计算最小高度的列
    - (NSInteger)minColumn {
        
        NSInteger minColumn = 0;
        CGFloat minHeight = [self.perColumnMaxHeights[0] floatValue];
        for (int i = 1; i < self.perColumnMaxHeights.count; i ++) {  
            CGFloat height = [self.perColumnMaxHeights[i] floatValue];
            if (height < minHeight) {
                minHeight = height;
                minColumn = i;
            }
        }
        return minColumn;
    }
    
    //计算最大高度的列 ,(用在设置 contensize)
    - (NSInteger)maxColumn {
        
        NSInteger maxColumn = 0;
        CGFloat maxHeight = [self.perColumnMaxHeights[0] floatValue];
        for (int i = 1; i < self.perColumnMaxHeights.count; i ++) {
            CGFloat height = [self.perColumnMaxHeights[i] floatValue];
            if (height > maxHeight) {
                maxHeight = height;
                maxColumn = i;
            }
        }
        return maxColumn;
    }
    
    
    - (CGSize)collectionViewContentSize {
        
        if (self.perColumnMaxHeights.count == 0) {
            return CGSizeZero;
        }
        return CGSizeMake(self.collectionView.bounds.size.width,  [self.perColumnMaxHeights[[self maxColumn]] floatValue] + _insets.bottom);
    }
    
    - (void)setHorzontalMargin:(CGFloat)horizontalMargin {
        
        _horizontalMargin = horizontalMargin;
    }
    
    - (void)setVerticalMargin:(CGFloat)verticalMargin{
        
        _verticalMargin = verticalMargin;
    }
    
    - (void)setMaxColumns:(NSInteger)maxColumns{
        if (maxColumns == 0) {
            return;
        }
        _maxColumns = maxColumns;
    }
    
    -(void)setInserts:(UIEdgeInsets)inserts {
        
        _insets = inserts;
    }
    
    @end
    

    UICollectionView水平缩放布局

    水平布局.png
    //使用
    - (void)initHorizenCollectionView {
        _myHorizontalView = ({
            //设置布局 : 流水布局(布局类在下面)
            DFHorizontalLayout *flowLayout = [[DFHorizontalLayout alloc]init];
            flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
            flowLayout.itemSize = CGSizeMake([UIScreen mainScreen].bounds.size.width/3.0, [UIScreen mainScreen].bounds.size.width/3.0);
            
            //创建 collectionView 初始化时加入布局
            UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 200, self.view.bounds.size.width, self.view.bounds.size.width/3.0)
                                                                 collectionViewLayout:flowLayout];
            collectionView.backgroundColor = [UIColor blackColor];
            collectionView.dataSource = self;
            [collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:collectionCellID1];
            [self.view addSubview:collectionView];
            collectionView;
        });
    }
    
    - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
          return 200;
    }
    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
        UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionCellID1 forIndexPath:indexPath];
        cell.backgroundColor = [UIColor yellowColor];
        return cell;
    }
    

    DFHorizontalLayout.h文件(继承UICollectionViewFlowLayout)

    /*!
     *  @brief 水平布局(从左到右)
     */
    @interface DFHorizontalLayout : UICollectionViewFlowLayout
    
    @end
    

    DFHorizontalLayout.m文件(实现文件)

    @implementation DFHorizontalLayout
    
    //返回区域内每一个元素的布局属性 (重写的话, 相当于 要给每一个元素增添属性)
    - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
        // 系统父类写的方法, 系统子类必须调用父类,进行执行(只是对部分属性进行修改,所以不必一个个进行设置布局属性)
        NSArray *layoutAtts =  [super layoutAttributesForElementsInRect:rect];
        CGFloat collectionViewCenterX = self.collectionView.bounds.size.width * 0.5;
        CGFloat contentOffsetX = self.collectionView.contentOffset.x;
        for (UICollectionViewLayoutAttributes *layoutAtt in layoutAtts) {
            CGFloat centerX = layoutAtt.center.x;
            // 形变值,根据当前cell 距离中心位置,的远近  进行反比例缩放。 (不要忘记算其偏移量的值。)
            CGFloat scale = 1 - ABS((centerX - collectionViewCenterX - contentOffsetX)/self.collectionView.bounds.size.width);
            // 给 布局属性  添加形变
            layoutAtt.transform = CGAffineTransformMakeScale(scale, scale);
        }
        return layoutAtts;
    }
    
    /**
     现在实现另一个功能.想让每次都有一个图片放在 collectionView 的中间,也就是总有一张大的图片.,也就是上图的情况. (需要让其停止拖拽的时候, 让图片的偏移量 进行一定的修改, 离中线最近的 cell, 移至中心). 关于偏移量的方法, 我们找到其相关方法,再次进行重写的
     */
    //通过目标移动的偏移量, 提取期望偏移量  (一般情况下,期望偏移量,就是 目标偏移量)
    - (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {
        
        //根据偏移量 , 确定区域
        CGRect rect = CGRectMake(proposedContentOffset.x, 0, self.collectionView.frame.size.width, self.collectionView.frame.size.height);
        //将屏幕所显示区域的 元素布局 取出。
        NSArray *layoutAtts = [super layoutAttributesForElementsInRect:rect];
        CGFloat minMargin = MAXFLOAT;
        CGFloat collectionViewCenterX = self.collectionView.frame.size.width * 0.5;
        CGFloat contentOffsetX = proposedContentOffset.x;
        //取出区域内元素, 并根据其中心位置, 与视图中心位置 进行比较, 比出最小的距离差
        for (UICollectionViewLayoutAttributes *layoutAtt in layoutAtts) {
            CGFloat margin = layoutAtt.center.x - contentOffsetX - collectionViewCenterX;
            if (ABS(margin) < ABS(minMargin)) {
                minMargin = margin;
            }
        }
        NSLog(@"%f",minMargin);
        //期望偏移量 加上差值, 让整体,沿差值 反方向移动,这样的话, 最近的一个,刚好在中心位置
        proposedContentOffset.x += minMargin;
        return proposedContentOffset;
    }
    
    /**
    //打开此处,为圆形布局,计算方式如下图
    // 进行圆形布局,设置其每个元素的相关因素(主要是它的 frame,中心点)
    - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
    {
        // 创建可变数组,用于储存所有的布局因素
        NSMutableArray *layoutAtts = [NSMutableArray array];
        // 取出对应布局中的 collectionView 的元素的数目(为的就是给一个个cell 独立设置其的布局)
        NSInteger count =  [self.collectionView numberOfItemsInSection:0];
        // 设置每个 cell 的高度和宽度
        CGFloat WH = 50;
        // 取出圆形视图的中心点 (也就是 collectionView 的中心点)
        CGFloat centerX = self.collectionView.frame.size.width * 0.5;
        CGFloat centerY = self.collectionView.frame.size.height * 0.5;
        // 设置 圆形布局半径
        CGFloat randius = centerY- 30;
        // 获得每个 cell 之间的间距 (所有 cell 平分了整个圆)
        CGFloat angelMargin = M_PI * 2 / count;
        // 遍历进行设置布局
        for (int i = 0; i < count ; i ++) {
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            //创建对应索引的布局
            UICollectionViewLayoutAttributes *layoutAtt = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
            //根据三角函数设置布局的中心点
            CGFloat a = sin(i * angelMargin) * randius;
            CGFloat b = cos(i * angelMargin) * randius;
            layoutAtt.center = CGPointMake(centerX + a, b+ centerY);
            layoutAtt.size = CGSizeMake(WH, WH);
            [layoutAtts addObject:layoutAtt];
        }
        return layoutAtts;
    }
    */
    
    // 是否允许 运行时,(在无效(未确定)的layout 情况下)改变bounds
    - (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
        
        return YES;
    }
    
    @end
    

    圆形计算图示

    x = sin(A*i)*R; y = cos(A*i)*R; =>frame = CGRectMake(centerX+x,centerY+y,宽度,高度);

    相关文章

      网友评论

          本文标题:UIKit_UICollectionView瀑布流,水平流水布局

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