美文网首页
自定义UICollectionViewLayout实现瀑布流

自定义UICollectionViewLayout实现瀑布流

作者: codermali | 来源:发表于2018-04-12 20:47 被阅读23次

在移动开发中,瀑布流应该非常普及了.我一直没有完整的写过一个瀑布流,今天搜集了一些资料,看了下系统的文档,大概实现了功能.中间也碰到了一些问题,现在记录下来,一方面方便自己以后回忆,另一反面也希望能帮到大家.

要用UICollectionView实现瀑布流,自定义UICollectionViewLayout和UICollectionViewFlowLayout都可以实现.

UICollectionViewLayout是一个抽象类,是UICollectionViewFlowLayout的父类.用来配置UICollectionView的布局.

UICollectionViewFlowLayout其实是一个系统为我们写好的流水布局.通过自定义UICollectionViewFlowLayout来实现瀑布流,更方便.比如说,系统已经帮我们实现了补充视图和装饰视图.

在这里,我选择的是自定义UICollectionViewLayout来实现瀑布流.根据文档,如果要使用它,需要继承它,并且重写以下几个方法.
  • collectionViewContentSize
    • 返回collectionView的滚动范围
  • layoutAttributesForElementsInRect:
    • 返回可视范围内所有cell的布局属性
  • layoutAttributesForItemAtIndexPath:
    • 返回指定indexPath处的cell的布局属性
  • layoutAttributesForSupplementaryViewOfKind:atIndexPath:
    • 返回补充视图的布局属性(如果有补充视图)
  • layoutAttributesForDecorationViewOfKind:atIndexPath:
    • 返回装饰视图的布局属性(如果有装饰视图)
  • shouldInvalidateLayoutForBoundsChange:
    • 当视图滚动时(可视范围变化时),是否更新视图
在实际应用中,我重写了以下四个方法.调用顺序从上到下
  • prepareLayout 该方法在每次布局需要更新(当collectionView第一次显示或者当布局失效)时调用.一般在里面做一些初始化的工作,进行基本的布局.
  • collectionViewContentSize
  • layoutAttributesForElementsInRect:(CGRect)rect
  • shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds
这个我有一个疑问,因为文档中提示需要重写layoutAttributesForItemAtIndexPath:方法,但是coding中,我发现这个方法从来没有调用过.我猜在UICollectionViewFlowLayout中是系统在layoutAttributesForElementsInRect:方法中调用了layoutAttributesForItemAtIndexPath:方法.而在我自定义的UICollectionViewLayout中,我并没有调用layoutAttributesForItemAtIndexPath:,因此不重写这个方法也可以实现功能.
具体思路如下:
首先一个前提就是各个cell宽度一致.根据总列数来计算cell的宽度.然后根据图片长宽比来检出cell的高度.然后,创建一个数组来保存各列cell的总高度,每次添加cell时,将cell添加到总高度最短的一列.以此类推,就可以计算出各个cell的x,y坐标.然后将各个cell的布局参数缓存起来,在需要时直接调用就行.
具体代码如下:

1.自定义UICollectionViewLayout,并开放接口,设置参数

/** 内边距 */
@property (nonatomic, assign) UIEdgeInsets sectionInsets;

/** 总列数 */
@property (nonatomic, assign) NSInteger numberOfColumns;

/** item之间的行间距 */
@property (nonatomic, assign) CGFloat minimumInteritemSpacing;

/** item之间的列间距 */
@property (nonatomic, assign) CGFloat minimumLineSpacing;

/** 代理属性 */
@property (nonatomic, weak) id<MLWaterflowLayoutDelegate> delegate;

2.定义代理属性,让代理实现获得每个cell的高度

@protocol MLWaterflowLayoutDelegate <NSObject>

/**
 计算indexPath位置上的item的高度
 @param width       item的宽度
 @param indexPath   item的位置
 @return            item的高度
 */
- (CGFloat)heightForItemWithWidth:(CGFloat) width AtIndexPath:(NSIndexPath *)indexPath;

@end

3.定义私人成员变量,用于计算

/** 存放所有item的布局属性 */
@property (nonatomic, strong) NSMutableArray *itemAttributesArray;

/** 存放所有列的高度 */
@property (nonatomic, strong) NSMutableArray *columnsHeightArray;

/** item的总数 */
@property (nonatomic, assign) NSInteger numberOfItems;

4.在prepareLayout中计算每个cell的布局,并保存

#pragma mark - 重写父类的布局方法
- (void)prepareLayout {
    NSLog(@"%s", __func__);
    [self initialColumnsHeightsArray];
    [self calculateAttributesForitems];
}

#pragma mark - 自定义方法
/** 初始化self.columnsHeightArray */
- (void)initialColumnsHeightsArray {
    //1.避免出错,先清空self.columnsHeightArray
    [self.columnsHeightArray removeAllObjects];
    //2.根据self.numberOfColumns来初始化self.columnsHeightArray
    for (NSInteger i = 0; i < self.numberOfColumns; i ++) {
        //为每一个item设置初始高度
        [self.columnsHeightArray addObject:@(self.sectionInsets.top)];
    }
}

/** 计算所有item的布局属性 */
- (void)calculateAttributesForitems {
    for (NSInteger i = 0; i < self.numberOfItems; i ++) {
        //根据总列数算出每一个item的宽度
        CGFloat itemWidth = ([UIScreen mainScreen].bounds.size.width - self.sectionInsets.left - (self.numberOfColumns - 1) * self.minimumInteritemSpacing - self.sectionInsets.right) / self.numberOfColumns;
        //拿到当前高度最小的列的索引
        NSInteger shortestIndex = [self getShortestColumnsIndex];
        //计算当前item的X坐标
        CGFloat itemX = self.sectionInsets.left + (itemWidth + self.minimumInteritemSpacing) * shortestIndex;
        //通过代理获得当前item的高度
        CGFloat itemHeight = 0;
        if ([self.delegate respondsToSelector:@selector(heightForItemWithWidth:AtIndexPath:)]) {
            itemHeight = [self.delegate heightForItemWithWidth:itemWidth AtIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        }
        //计算当前item的Y坐标
        CGFloat itemY = [self.columnsHeightArray[shortestIndex] floatValue] + self.minimumLineSpacing;
        //将item的布局属性保存到数组
        UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:[NSIndexPath indexPathForRow:i inSection:0]];
        attributes.frame = CGRectMake(itemX, itemY, itemWidth, itemHeight);
        [self.itemAttributesArray addObject:attributes];
        //将高度保存到columnsHeightArray数组中
        [self.columnsHeightArray replaceObjectAtIndex:shortestIndex withObject:@(itemY + itemHeight)];
    }
}

5.在layoutAttributesForElementsInRect中返回可见视图中的cell的布局属性

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    NSLog(@"%s", __func__);
    //创建一个数组来存放显示在屏幕中的item的attributes
    NSMutableArray *tempArr = [NSMutableArray array];
    //遍历self.itemAttributesArray
    for (UICollectionViewLayoutAttributes *attributes in self.itemAttributesArray) {
        //判断item是否显示在屏幕中
        if (CGRectIntersectsRect(rect, attributes.frame)) {
            //如果是,保存到tempArr
            [tempArr addObject:attributes];
        }
    }
    return tempArr;
}

6.在collectionViewContentSize中返回UICollectionView的contentSize

- (CGSize)collectionViewContentSize {
    NSLog(@"%s", __func__);
    return CGSizeMake([UIScreen mainScreen].bounds.size.width, self.sectionInsets.bottom + [self.columnsHeightArray[[self getHighestColumnsIndex]] floatValue]);
}

7.在shouldInvalidateLayoutForBoundsChange中判断在滚动时,是否需要刷新布局属性.如果需要,那么会调用prepareLayout方法,重新布局

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    NSLog(@"%s", __func__);
    return NO;
}

Github上demo地址

相关文章

网友评论

      本文标题:自定义UICollectionViewLayout实现瀑布流

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