瀑布流layout自定義

兩個(gè)文件PNWaterfallLayout.h PNWaterfallLayout.m也比較容易理解本鸣,繼承自UICollectionViewLayout類。

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

1、提前計(jì)算好喜德,itempositioncollectionViewsize逛绵,這個(gè)方法在初始化layout后自動(dòng)調(diào)用,可以在該方法中初始化一些自定義的變量參數(shù)
- (void)prepareLayout;
2频伤、返回collectionViewcontentSize (注:事先需要找出最大的y值)
- (CGSize)collectionViewContentSize;
3恳谎、返回某個(gè)特定區(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  每個(gè)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è)置默認(rèn)值惠爽,為了防止用戶沒有給變量賦值

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

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

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

- (void)prepareLayout
{
    [super prepareLayout];
    // 默認(rèn)值
    // 列數(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婚肆、返回某個(gè)特定區(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對(duì)應(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
    // 計(jì)算位置
    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)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市糟港,隨后出現(xiàn)的幾起案子攀操,更是在濱河造成了極大的恐慌,老刑警劉巖秸抚,帶你破解...
    沈念sama閱讀 216,470評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件速和,死亡現(xiàn)場離奇詭異,居然都是意外死亡剥汤,警方通過查閱死者的電腦和手機(jī)颠放,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,393評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來吭敢,“玉大人碰凶,你說我怎么就攤上這事。” “怎么了欲低?”我有些...
    開封第一講書人閱讀 162,577評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵辕宏,是天一觀的道長。 經(jīng)常有香客問我砾莱,道長匾效,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,176評(píng)論 1 292
  • 正文 為了忘掉前任恤磷,我火速辦了婚禮面哼,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘扫步。我一直安慰自己魔策,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,189評(píng)論 6 388
  • 文/花漫 我一把揭開白布河胎。 她就那樣靜靜地躺著闯袒,像睡著了一般。 火紅的嫁衣襯著肌膚如雪游岳。 梳的紋絲不亂的頭發(fā)上政敢,一...
    開封第一講書人閱讀 51,155評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音胚迫,去河邊找鬼喷户。 笑死,一個(gè)胖子當(dāng)著我的面吹牛访锻,可吹牛的內(nèi)容都是我干的褪尝。 我是一名探鬼主播,決...
    沈念sama閱讀 40,041評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼期犬,長吁一口氣:“原來是場噩夢啊……” “哼河哑!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起龟虎,我...
    開封第一講書人閱讀 38,903評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤璃谨,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后鲤妥,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體佳吞,經(jīng)...
    沈念sama閱讀 45,319評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,539評(píng)論 2 332
  • 正文 我和宋清朗相戀三年旭斥,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了容达。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片古涧。...
    茶點(diǎn)故事閱讀 39,703評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡垂券,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情菇爪,我是刑警寧澤算芯,帶...
    沈念sama閱讀 35,417評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站凳宙,受9級(jí)特大地震影響熙揍,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜氏涩,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,013評(píng)論 3 325
  • 文/蒙蒙 一届囚、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧是尖,春花似錦意系、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,664評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至兜辞,卻和暖如春迎瞧,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背逸吵。 一陣腳步聲響...
    開封第一講書人閱讀 32,818評(píng)論 1 269
  • 我被黑心中介騙來泰國打工凶硅, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人扫皱。 一個(gè)月前我還...
    沈念sama閱讀 47,711評(píng)論 2 368
  • 正文 我出身青樓咏尝,卻偏偏與公主長得像,于是被迫代替她去往敵國和親啸罢。 傳聞我的和親對(duì)象是個(gè)殘疾皇子编检,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,601評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容