美文网首页瀑布流
瀑布流layout自定义

瀑布流layout自定义

作者: DSA碼侬 | 来源:发表于2017-02-10 17:00 被阅读39次

    两个文件PNWaterfallLayout.h PNWaterfallLayout.m也比较容易理解,继承自UICollectionViewLayout类。

    自定义layout需要实现三个方法:

    1、提前计算好,itempositioncollectionViewsize,这个方法在初始化layout后自动调用,可以在该方法中初始化一些自定义的变量参数
    - (void)prepareLayout;
    
    2、返回collectionViewcontentSize (注:事先需要找出最大的y值)
    - (CGSize)collectionViewContentSize;
    
    3、返回某个特定区域的布局的属性的,返回所有元素的布局rect: 所有元素的布局(header+item+footer
    - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect;
    

    PNWaterfallLayout.h文件:

    1、定义协议protocol PNWaterfallLayoutDelegate
     /// 求item得高度--传width是为了显示图片成比例不变形
     - (CGFloat)collectionView:(UICollectionView *)collection layout:(PNWaterfallLayout *)layout heightForWidth:(CGFloat)width atIndexPath:(NSIndexPath *)indexPath;
     /// 求header得size
     - (CGSize)collectionView:(UICollectionView *)collection layout:(PNWaterfallLayout *)layout referenceSizeForHeaderInSection:(NSInteger)section;
     /// 求footer得size
     - (CGSize)collectionView:(UICollectionView *)collection layout:(PNWaterfallLayout *)layout referenceSizeForFooterInSection:(NSInteger)section;
    
    定义属性:为了在外部更够修改赋值
    /// itemSize  每个item的大小
    @property(nonatomic, assign) CGSize itemSize;
    /// 行间距  行与行之间的间距
    @property(nonatomic, assign) CGFloat lineSpace;
    /// 列间距  列与列之间的间距
    @property(nonatomic, assign) CGFloat InteritemSpace;
    #warning 每组四周的insets
    @property(nonatomic, assign) UIEdgeInsets sectionInset;
    /// 列数
    @property(nonatomic, assign) CGFloat colCount;
    /// 代理
    @property(nonatomic,weak) id<PNWaterfallLayoutDelegate> delegate;
    

    PNWaterfallLayout.m文件

    设置默认值,为了防止用户没有给变量赋值

    static const CGFloat inset = 10;
    static const CGFloat colCount = 3;
    
    @interface PNWaterfallLayout ()
    /// 通过计算用于存放每一列的最大Y值字典
    @property(nonatomic, strong) NSMutableDictionary *columnMaxYDic;
    @end
    
    重写三个方法

    1、- (void)prepareLayout初始化layout时候自动调用

    - (void)prepareLayout
    {
        [super prepareLayout];
        // 默认值
        // 列数
        self.colCount = self.colCount?self.colCount:colCount; 
        // 行间距
        self.lineSpace = self.lineSpace?self.lineSpace:inset; 
        // 列间距
        self.InteritemSpace = self.InteritemSpace?self.InteritemSpace:inset; 
        // 组inset
        self.sectionInset = UIEdgeInsetsMake(inset, inset, inset, inset); 
        // 字典初始化
        self.columnMaxYDic = [NSMutableDictionary dictionary]; 
    }
    

    2、返回collectionViewcontentSize 先需要找出列中最大的 y值

    - (CGSize)collectionViewContentSize
    {
        [super collectionViewContentSize];
        __block NSNumber *maxCol = @(0);
        [self.columnMaxYDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
          if ([obj floatValue] > [self.columnMaxYDic[maxCol] floatValue]) {
            maxCol = key; // 记录最大y的列索引
        }
    }];
    
    return CGSizeMake(0, [self.columnMaxYDic[maxCol] floatValue]);
    }
    

    3、返回某个特定区域的布局的属性的,返回所有元素的布局
    rect: 所有元素的布局(header+item+footer

    - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
    {
        /// 初始化每一列的最大Y值 @0
        for (int i = 0; i < self.colCount; i ++) {
          self.columnMaxYDic[@(i)] = @0;
        }
    
        // 获得所有元素的属性
    NSMutableArray *attrsArray = [NSMutableArray array];
    for (NSInteger i = 0; i < [self.collectionView numberOfSections]; i++) {
        // 1、header
        UICollectionViewLayoutAttributes *headerAtts = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader atIndexPath:[NSIndexPath indexPathForItem:0 inSection:i]];
        [attrsArray addObject:headerAtts];
        
        //2、 items
        NSInteger count = [self.collectionView numberOfItemsInSection:i];
        for (NSInteger j = 0; j < count; j++) {
            UICollectionViewLayoutAttributes *itemAtts = [self layoutAttributesForItemAtIndexPath:[NSIndexPath indexPathForItem:j inSection:i]];
            [attrsArray addObject:itemAtts];
        }
        
        //3、 footer
        UICollectionViewLayoutAttributes *footerAtts = [self layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionFooter atIndexPath:[NSIndexPath indexPathForItem:0 inSection:i]];
        [attrsArray addObject:footerAtts];
        
       }
    return attrsArray;
     }
    

    获得item attributes-----根据不同的indexPath给出布局

    - (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
    {
        __block NSNumber *minCol = @(0);
       // 找出三列中,最小的Y的索引 ,遍历存放最大Y值得字典
        [self.columnMaxYDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([obj floatValue] < [self.columnMaxYDic[minCol] floatValue]) {
            minCol = key;
        }
    }];
    
    // 宽度
    CGFloat itemWidth = ([UIScreen mainScreen].bounds.size.width - self.sectionInset.left - self.sectionInset.right - (self.colCount-1) * self.lineSpace) / self.colCount;
    // 高度
    CGFloat itemHeight = 0;
    if ([self.delegate respondsToSelector:@selector(collectionView:layout:heightForWidth:atIndexPath:)]) {
        itemHeight = [self.delegate collectionView:self.collectionView layout:self heightForWidth:itemWidth atIndexPath:indexPath];
    }
    
    // 更新最小Y对应列的高度
    CGFloat x = self.sectionInset.left + (itemWidth + self.InteritemSpace)* [minCol intValue];
    
    CGFloat space = 0;
    if (indexPath.item < self.colCount) { // 最顶部的item
        space = 0;
    }else
    {
        // 非顶部的item
        space = self.lineSpace;
    }
    
    CGFloat y = [self.columnMaxYDic[minCol] floatValue] + space;
    self.columnMaxYDic[minCol] = @(y + itemHeight);
    #warning cell item
        // 计算位置
        UICollectionViewLayoutAttributes *attrItem = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        attrItem.frame = CGRectMake(x, y, itemWidth, itemHeight);
    
    return attrItem;
    }
    

    获得headerfooter attributes

    - (UICollectionViewLayoutAttributes *)layoutAttributesForSupplementaryViewOfKind:(NSString *)elementKind atIndexPath:(NSIndexPath *)indexPath
    {
        // 找出最高的列
        __block NSNumber *maxCol = @(0);
        [self.columnMaxYDic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            if ([obj floatValue] > [self.columnMaxYDic[maxCol] floatValue]) {
                maxCol = key;
            }
        }];
    
    // headerView
    if ([UICollectionElementKindSectionHeader isEqualToString:elementKind]) {
        UICollectionViewLayoutAttributes *attri = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionHeader withIndexPath:indexPath];
        // 求出header的size
        CGSize size = CGSizeZero;
        if ([self.delegate respondsToSelector:@selector(collectionView:layout:referenceSizeForHeaderInSection:)]) {
           size = [self.delegate collectionView:self.collectionView layout:self referenceSizeForHeaderInSection:indexPath.section];
        }
        
        CGFloat x = self.sectionInset.left;
        CGFloat y = [self.columnMaxYDic[maxCol] floatValue] + self.sectionInset.top;
        
        // 更新所有列的高度
        for (NSNumber *key in self.columnMaxYDic.allKeys) {
            self.columnMaxYDic[key] = @(y + size.height);
        }
        
        attri.frame = CGRectMake(x, y, size.width, size.height);
        return attri;
        
    }
    
    // footerView
    UICollectionViewLayoutAttributes *attri = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionFooter withIndexPath:indexPath];
    // 求出footerView的size
    CGSize size = CGSizeZero;
    if ([self.delegate respondsToSelector:@selector(collectionView:layout:referenceSizeForFooterInSection:)]) {
      size = [self.delegate collectionView:self.collectionView layout:self referenceSizeForFooterInSection:indexPath.section];
        }
        CGFloat x = self.sectionInset.left;
        CGFloat y = [self.columnMaxYDic[maxCol] floatValue];
        // 更新所有列的高度
        for (NSNumber *key in self.columnMaxYDic.allKeys) {
        self.columnMaxYDic[key] = @(y + size.height);
        }
        attri.frame = CGRectMake(x, y, size.width, size.height);
        return attri;
        }
        @end

    相关文章

      网友评论

        本文标题:瀑布流layout自定义

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