瀑布流的实现

作者: IIronMan | 来源:发表于2016-10-10 01:55 被阅读194次

    简介:瀑布流的实现前提是后台给返回图片的高度宽度

    效果图

    瀑布流.gif

    1.先给大家讲讲怎么使用这个封装

    • 1.瀑布流主要是layout的布局
      你可以把类CWWaterViewLayout.h拖走,里面有几个属性
      /**
       *  collectionView上下左右之间的间距
       */
      @property(nonatomic,assign) UIEdgeInsets sectionInset;
    
      /**
       *  每一列之间的间距
       */
      @property(nonatomic,assign) CGFloat columnMargin1;
    
      /**
       *  每一行之间的间距
       */
      @property(nonatomic,assign) CGFloat rowMargin1;
    
      /**
       *  告诉外界你想显示多少列
       */
      @property(nonatomic,assign) int columnsCount;
    

    默认情况下全是10

    • 2.cell的布局自己设计了

    • 3.传比例(这个方法需要实现)

      #pragma mark - <CWWaterViewLayoutDelegate>的代理方法
      -(CGFloat)waterflowLayout:(CWWaterViewLayout *)waterViewLayout heightForWidth:(CGFloat)width atIndexPath:(NSIndexPath *)indexPath
      {
         ShopModel *shopmodel = self.tempArray[indexPath.item];
         /**
          *  取出来宽高
          */
        NSString *shopH = [NSString stringWithFormat:@"%@",shopmodel.H];
        NSString *shopW = [NSString stringWithFormat:@"%@",shopmodel.W];
        /**
          *  转化为float类型
          */
        CGFloat shopHValue = [shopH floatValue];
        CGFloat shopWValue = [shopW floatValue];
        /**
         *  返回比例计算的高度
         */
        return shopHValue / shopWValue * width;
      }
      

    2.重要的是CWWaterViewLayout.m里面的布局计算才是瀑布流的核心代码

    #pragma mark5.  尺寸的计算
    -(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
    {
    /**
     *  假设最短的那一列是第0列
     */
    __block NSString *minYColun = @"0";
    
    [self.maxYdict enumerateKeysAndObjectsUsingBlock:^(NSString *column,NSNumber *maxY, BOOL * _Nonnull stop) {
        
        if ([maxY floatValue] < [self.maxYdict[minYColun] floatValue] ) {
            
            minYColun = column;
        }
    }];
    /**
     *  计算宽度
     */
    CGFloat width =  (self.collectionView.frame.size.width - self.sectionInset.left - self.sectionInset.right - (self.columnsCount - 1) * self.columnMargin1)/self.columnsCount;
    /**
     *  高度
     */
    CGFloat height = [self.delegate waterflowLayout:self heightForWidth:width atIndexPath:indexPath];
    
    /**
     *  计算x和y
     */
    CGFloat x = self.sectionInset.left + (width + self.columnMargin1) * [minYColun floatValue];
    CGFloat y = [self.maxYdict[minYColun]floatValue] + self.rowMargin1;
    
    /**
     *  更新这一列的最大Y值
     */
      self.maxYdict[minYColun] = @(y + height);
    
      UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
      attrs.frame = CGRectMake(x, y, width, height);
    
      return attrs;
    }
    

    后记:具体的您看代码,我都进行了注释

    王冲的瀑布流 密码: 4seg

    相关文章

      网友评论

        本文标题:瀑布流的实现

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