瀑布流layout自定義

兩個文件PNWaterfallLayout.h PNWaterfallLayout.m也比較容易理解,繼承自UICollectionViewLayout類。

自定義layout需要實現(xiàn)三個方法:

1、提前計算好,itempositioncollectionViewsize,這個方法在初始化layout后自動調(diào)用,可以在該方法中初始化一些自定義的變量參數(shù)
- (void)prepareLayout;
2、返回collectionViewcontentSize (注:事先需要找出最大的y值)
- (CGSize)collectionViewContentSize;
3、返回某個特定區(qū)域的布局的屬性的,返回所有元素的布局rect: 所有元素的布局(header+item+footer
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect;

PNWaterfallLayout.h文件:

1、定義協(xié)議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;
/// 列數(shù)
@property(nonatomic, assign) CGFloat colCount;
/// 代理
@property(nonatomic,weak) id<PNWaterfallLayoutDelegate> delegate;

PNWaterfallLayout.m文件

設(shè)置默認值,為了防止用戶沒有給變量賦值

static const CGFloat inset = 10;
static const CGFloat colCount = 3;

@interface PNWaterfallLayout ()
/// 通過計算用于存放每一列的最大Y值字典
@property(nonatomic, strong) NSMutableDictionary *columnMaxYDic;
@end
重寫三個方法

1、- (void)prepareLayout初始化layout時候自動調(diào)用

- (void)prepareLayout
{
    [super prepareLayout];
    // 默認值
    // 列數(shù)
    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、返回某個特定區(qū)域的布局的屬性的,返回所有元素的布局
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-----根據(jù)不同的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對應(yīng)列的高度
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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容