iOS - 瀑布流簡單的實現(xiàn)

前言

平時沒事也喜歡逛一些技術(shù)網(wǎng)站,而瀑布流因為其炫酷的視覺效果(其實就是模仿)和樣式使其成為ios當中比較火熱的一種技術(shù)来吩。
在最近的一個項目中弟疆,生活也對我這個菜鳥下了毒手盗冷,要求實現(xiàn)瀑布流(WTF。柑司。锅劝。)吐槽歸吐槽但是效果還是得做出來故爵。。劲室。
現(xiàn)在我來介紹一下我的實現(xiàn)思路(其實是參考網(wǎng)上案例??)

初步接觸UICollectionView的小伙伴們肯定都知道蘋果官方為我們封裝好的UICollectionViewFlowLayout痹籍,在很多情況下我們使用UICollectionViewFlowLayout就可以實現(xiàn)需求了晦鞋。
下面的列子簡單實用UICollectionViewFlowLayout實現(xiàn)效果

//設(shè)置流水布局
  UICollectionViewFlowLayout *layout = ({
      //設(shè)置流水布局
      UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init] ;
      layout.itemSize = CGSizeMake(itemWH, itemWH) ;
      layout.minimumInteritemSpacing = margin; // 最小間距
      layout.minimumLineSpacing = margin; //最小行距
      layout ;
  }) ;
  
  //創(chuàng)建CollectionView
  UICollectionView *collocetView = ({
      //創(chuàng)建CollectionView
      UICollectionView *collocetView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 10, kScreenW, 450) collectionViewLayout:layout] ;
      collocetView.backgroundColor= [UIColor whiteColor ];
      //設(shè)置數(shù)據(jù)源和代理
      collocetView.delegate = self ;
      collocetView.dataSource = self ;
      collocetView.alwaysBounceHorizontal = YES;
      
      self.collectionView = collocetView ;
      
      //注冊cell 一定要做
      [collocetView registerClass:[SWCollectionViewCell class] forCellWithReuseIdentifier:itemID] ;
      collocetView ;
  });

 //注冊頭部
    [self.collectionView registerClass:[SWCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:heardID] ;
    
    //注冊尾部
    [self.collectionView registerClass:[SWCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:heardID];
這里得強調(diào)一下UICollectionView的cell和頭尾試圖通常都是注冊實現(xiàn)的。娜谊。纱皆。近迁。

二. 瀑布流的實現(xiàn)思路:

  1. 控件選擇:現(xiàn)在實現(xiàn)瀑布流主流的思路是用UICollectionView來實現(xiàn)鉴竭,優(yōu)點不言而喻搏存,因為其豐富的API和類似tableView的復用機制等 矢洲。。蛆橡【蚱可能也有人用srollView實現(xiàn)(我不會葱轩,,垃喊,唉~)袜炕。

  2. 因為官方的UICollectionViewFlowLayout是繼承自UICollectionViewLayout偎窘,所以我們也可以參照官方的實現(xiàn)瀑布流效果

  3. 現(xiàn)在我們需要指定滾動方向溜在、默認列數(shù)掖肋、行間距志笼、列間距、以及指定cell的寬度itemWidth還需要通過方法計算高度

import "SWWaterFallLayout.h"

@class SWWaterFallLayout ;
//1.定義協(xié)議
@protocol SWWaterFallLayoutDelegate<NSObject>
//必須實現(xiàn)的方法
@required
/**
 每一列的寬度
 */
- (CGFloat)waterFallLayout:(SWWaterFallLayout *)waterFallLayout heightForItemAtIndexPath:(NSUInteger)indexPath itemWidth:(CGFloat)itemWidth ;

//可選
@optional
/**
 一共有多少列
 */
-(NSInteger)columnCountWaterFallLayout:(SWWaterFallLayout *)waterFallLayout ;
/**
 每一列的間距
 */
-(CGFloat)columnMarginWaterFallLayout:(SWWaterFallLayout *)waterFallLayout ;
/**
 每一行的間距
 */
-(CGFloat)rowMarginWaterFallLayout:(SWWaterFallLayout *)waterFallLayout ;
/**
 每一個Item的內(nèi)間距
 */
-(UIEdgeInsets)edgeInsetsInWaterFallLayout:(SWWaterFallLayout *)waterFallLayout ;

@end
@interface SWWaterFallLayout : UICollectionViewLayout

- (NSUInteger)colunmCount;
- (CGFloat)columnMargin;
- (CGFloat)rowMargin;
- (UIEdgeInsets)edgeInsets;

//2.聲明代理屬性
@property(nonatomic,weak) id<SWWaterFallLayoutDelegate> delegate ;
  1. 可以提供一個數(shù)組attrsArr存放所有的布局屬性,columnHeights存放所有列的當前高度

import "SWWaterFallLayout.h"

/** 默認的列數(shù)    */
static const CGFloat SWDefaultColunmCount = 3;

/** 每一列之間的間距    */
static const CGFloat SWDefaultColunmMargin = 10;

/** 每一行之間的間距    */
static const CGFloat SWDefaultRowMargin = 10;

/** 內(nèi)邊距    */
static const UIEdgeInsets SWDefaultEdgeInsets = {10,10,10,10};

@interface SWWaterFallLayout ()
/** 存放所有的布局屬性 */
@property (nonatomic, strong) NSMutableArray * attrsArr;
/** 存放所有列的當前高度 */
@property (nonatomic, strong) NSMutableArray *columnHeights;
/** 內(nèi)容的高度 */
@property (nonatomic, assign) CGFloat contentHeight;

@end

@implementation SWWaterFallLayout

- (NSMutableArray *)attrsArr{
    if (!_attrsArr) {
        _attrsArr = [NSMutableArray array];
    }
    return _attrsArr;
}

- (NSMutableArray *)columnHeights{
    if (!_columnHeights) {
        _columnHeights = [NSMutableArray array];
    }
    
    return _columnHeights;
}

#pragma mark - 數(shù)據(jù)處理
/**
 * 列數(shù)
 */
-(NSUInteger)colunmCount{
    if ([self.delegate respondsToSelector:@selector(columnCountWaterFallLayout:)]) {
        return [self.delegate columnCountWaterFallLayout:self] ;
    }else{
        return SWDefaultColunmCount ;
    }
}

/**
 * 行間距
 */
- (CGFloat)rowMargin{
    if ([self.delegate respondsToSelector:@selector(rowMarginWaterFallLayout:)]) {
        return [self.delegate rowMarginWaterFallLayout:self];
    }else{
        return SWDefaultRowMargin;
    }
}

/**
 * 列間距
 */
- (CGFloat)columnMargin{
    if ([self.delegate respondsToSelector:@selector(columnMarginWaterFallLayout:)]) {
        return [self.delegate columnMarginWaterFallLayout:self];
    }else{
        return SWDefaultColunmMargin;
    }
}

/**
 * item的內(nèi)邊距
 */
- (UIEdgeInsets)edgeInsets{
    if ([self.delegate respondsToSelector:@selector(edgeInsetsInWaterFallLayout:)]) {
        return [self.delegate edgeInsetsInWaterFallLayout:self];
    }else{
        return SWDefaultEdgeInsets;
    }
}

/**
 * 初始化
 */
- (void)prepareLayout{
    
    [super prepareLayout];
    //內(nèi)容的高度
    self.contentHeight = 0;
    
    // 清除之前計算的所有高度
    [self.columnHeights removeAllObjects];
    
    // 設(shè)置每一列默認的高度
    for (NSInteger i = 0; i < SWDefaultColunmCount ; i ++) {
        [self.columnHeights addObject:@(SWDefaultEdgeInsets.top)];
    }
    // 清楚之前所有的布局屬性
    [self.attrsArr removeAllObjects];
    
    // 開始創(chuàng)建每一個cell對應的布局屬性
    NSInteger count = [self.collectionView numberOfItemsInSection:0] ;
    
    for (int i = 0; i < count; i++) {
        // 創(chuàng)建位置
        NSIndexPath * indexPath = [NSIndexPath indexPathForItem:i inSection:0] ;
        
        // 獲取indexPath位置上cell對應的布局屬性
        UICollectionViewLayoutAttributes * attrs = [self layoutAttributesForItemAtIndexPath:indexPath] ;
        
        [self.attrsArr addObject:attrs] ;
    }
}

/**
 * 返回indexPath位置cell對應的布局屬性
 Attributes :屬性
 */
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath{
    // 創(chuàng)建布局屬性
    UICollectionViewLayoutAttributes * attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
    
    //collectionView的寬度
    CGFloat collectionViewW = self.collectionView.frame.size.width;
    // 設(shè)置布局屬性的frame
    CGFloat cellW = (collectionViewW - self.edgeInsets.left - self.edgeInsets.right - (self.colunmCount - 1) * self.columnMargin) / self.colunmCount ;
    
    CGFloat cellH = [self.delegate waterFallLayout:self heightForItemAtIndexPath:indexPath.item itemWidth:cellW];
    // 找出最短的那一列
    NSInteger destColumn = 0;
    CGFloat minColumnHeight = [self.columnHeights[0] doubleValue];
    
    for (int i = 1; i < SWDefaultColunmCount; i++) {
        
        // 取得第i列的高度
        CGFloat columnHeight = [self.columnHeights[i] doubleValue];
        //判斷是否替換最小的列寬
        if (minColumnHeight > columnHeight) {
            minColumnHeight = columnHeight;
            destColumn = I;
        }
    }
    CGFloat cellX = self.edgeInsets.left + destColumn * (cellW + self.columnMargin);
    CGFloat cellY = minColumnHeight;
    if (cellY != self.edgeInsets.top) {
        
        cellY += self.rowMargin;
    }
    attrs.frame = CGRectMake(cellX, cellY, cellW, cellH);
    
    // 更新最短那一列的高度
    self.columnHeights[destColumn] = @(CGRectGetMaxY(attrs.frame));
    
    // 記錄內(nèi)容的高度 - 即最長那一列的高度
    CGFloat maxColumnHeight = [self.columnHeights[destColumn] doubleValue];
    if (self.contentHeight < maxColumnHeight) {
        self.contentHeight = maxColumnHeight;
    }
    
    return attrs;
}

/**
 * 決定cell的高度
 */
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    
    return self.attrsArr;
}

/**
 * 內(nèi)容的高度
 */
- (CGSize)collectionViewContentSize{
    
        CGFloat maxColumnHeight = [self.columnHeights[0] doubleValue];
        for (int i = 0; i < SWDefaultColunmCount; i++) {
    
            // 取得第i列的高度
            CGFloat columnHeight = [self.columnHeights[i] doubleValue];
    
            if (maxColumnHeight < columnHeight) {
                maxColumnHeight = columnHeight;
            }
    
        }
    
    return CGSizeMake(0, self.contentHeight + self.edgeInsets.bottom);
}

@end

最后在控制器中實現(xiàn)將collectView的layout設(shè)置成自定義的layout其他不變,就行啦郎楼。窒悔。敌买。。

瀑布流

吐槽:加班到爆炸啦~??

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市芙粱,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌脱货,老刑警劉巖律姨,帶你破解...
    沈念sama閱讀 217,509評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件扣孟,死亡現(xiàn)場離奇詭異荣赶,居然都是意外死亡鸽斟,警方通過查閱死者的電腦和手機湾盗,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,806評論 3 394
  • 文/潘曉璐 我一進店門格粪,熙熙樓的掌柜王于貴愁眉苦臉地迎上來帐萎,“玉大人胜卤,你說我怎么就攤上這事〕憾危” “怎么了舰攒?”我有些...
    開封第一講書人閱讀 163,875評論 0 354
  • 文/不壞的土叔 我叫張陵摩窃,是天一觀的道長猾愿。 經(jīng)常有香客問我鹦聪,道長泽本,這世上最難降的妖魔是什么姻僧? 我笑而不...
    開封第一講書人閱讀 58,441評論 1 293
  • 正文 為了忘掉前任段化,我火速辦了婚禮,結(jié)果婚禮上雄嚣,老公的妹妹穿的比我還像新娘缓升。我一直安慰自己,他們只是感情好骇吭,可當我...
    茶點故事閱讀 67,488評論 6 392
  • 文/花漫 我一把揭開白布燥狰。 她就那樣靜靜地躺著龙致,像睡著了一般顷链。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上嗤练,一...
    開封第一講書人閱讀 51,365評論 1 302
  • 那天榛了,我揣著相機與錄音,去河邊找鬼煞抬。 笑死霜大,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的此疹。 我是一名探鬼主播僧诚,決...
    沈念sama閱讀 40,190評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼遮婶,長吁一口氣:“原來是場噩夢啊……” “哼蝗碎!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起旗扑,我...
    開封第一講書人閱讀 39,062評論 0 276
  • 序言:老撾萬榮一對情侶失蹤蹦骑,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后眠菇,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體捎废,經(jīng)...
    沈念sama閱讀 45,500評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡辐益,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,706評論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了垦垂。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片乔外。...
    茶點故事閱讀 39,834評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡差购,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出稳析,到底是詐尸還是另有隱情彰居,我是刑警寧澤,帶...
    沈念sama閱讀 35,559評論 5 345
  • 正文 年R本政府宣布关筒,位于F島的核電站睡榆,受9級特大地震影響匾鸥,放射性物質(zhì)發(fā)生泄漏奴愉。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,167評論 3 328
  • 文/蒙蒙 一檀头、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧廊镜,春花似錦虫溜、人聲如沸容为。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,779評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽急膀。三九已至,卻和暖如春行瑞,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背氧吐。 一陣腳步聲響...
    開封第一講書人閱讀 32,912評論 1 269
  • 我被黑心中介騙來泰國打工豁翎, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留心剥,地道東北人。 一個月前我還...
    沈念sama閱讀 47,958評論 2 370
  • 正文 我出身青樓弊仪,卻偏偏與公主長得像,于是被迫代替她去往敵國和親颓鲜。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,779評論 2 354

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