iOS開發--瀑布流的簡單實現方法之一

瀑布流就是我們經常看到的參差不齊的多欄布局,這種布局出現在國內外大大小小的網站上,很多移動端的頁面布局也都選擇了這種方式,隨意的頁面布局卻得到不隨意的效果,增強了很好的用戶體驗. 這種布局適合于小數據塊,每個數據塊內容相近且沒有側重。通常,隨著頁面滾動條向下滾動,這種布局還會不斷加載數據塊并附加至當前尾部。
實現瀑布流的方式有很多,我們今天就簡單的介紹一種利用UICollectionView的實現效果.
瀑布流的實現原理就是設定每列上顯示的item的寬度是一定的,至于高度則根據原始圖片的比例進行相應的處理 遵循一個條件 :
高度/寬度 = 壓縮后高度/壓縮后寬度 (寬度的多少可以有這個式子計算所得)

對于UICollectionView的一些基本知識在此就不在累述, 我們直接進入正題.
首先,我們自定義一個WaterFallCollectionViewCell 繼承自UICollectionViewCell

.h
#import <UIKit/UIKit.h>
@interface WaterFallCollectionViewCell : UICollectionViewCell
//在此我們給出一個UIImage的屬性來展示圖片自
@property (nonatomic, strong) UIImage *image;
@end

.m
#import "WaterFallCollectionViewCell.h"
@implementation WaterFallCollectionViewCell
- (void)setImage:(UIImage *)image{
    if (_image != image) {
        _image = image;
    }
    [self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect{
    float newHeight = _image.size.height / _image.size.width * 100;
    [_image drawInRect:CGRectMake(0, 0, 100, newHeight)];
}
@end

我們創建collectionView的時候是需要和布局對象結合使用的, 我們自定義一個布局對象 WaterFallFlowLayout 繼承自UICollectionViewFlowLayout
并聲明其一下幾個屬性

@property (nonatomic, assign) id<UICollectionViewDelegateFlowLayout> delegate;//其代理對象
@property (nonatomic, assign) NSInteger cellCount;//包含cell的個數
@property (nonatomic, strong) NSMutableArray *colArr;//存放每一個列的高度
@property (nonatomic, strong) NSMutableDictionary *attributeDict;//存放cell的位置信息

我們在WaterFallFlowLayout.m文件里實現WaterFallFlowLayout方法,布局對象準備布局的時候回調用此方法

//準備布局:得到cell的總個數,為每個cell確定自己的位置
CGFloat const colCount = 3; //設定多少列
- (void)prepareLayout{
    [super prepareLayout];

//初始化相關數據
    _colArr = [NSMutableArray array];
    _attributeDict = [NSMutableDictionary dictionary];
    self.delegate = (id<UICollectionViewDelegateFlowLayout>)self.collectionView.delegate;

   //獲取cell的總個數
    _cellCount = [self.collectionView numberOfItemsInSection:0];
    if (_cellCount == 0) {
        return; 
    }
    float top = 0;

    for (int i = 0; i < colCount; i++) { // colCount 表示列數
        [_colArr addObject:[NSNumber numberWithFloat:top]];
    }
    //循環調用layoutForItemAtIndexPath方法,為每個cell布局,將indexPath傳入,作為布局字典的key
    //layoutAttributesForItemAtIndexPath方法的實現,這里用到了一個布局字典,其實就是將每個cell的位置信息與indexPath相對應,將它們放到字典中,方便后面視圖的檢索
    for (int i = 0; i < _cellCount; i++) {
        [self layoutItemAtIndexPath:[NSIndexPath indexPathForItem:i inSection:0]];
    }
}

layoutItemAtIndexPath:方法的實現

//此方法會多次調用,為每個cell布局
- (void)layoutItemAtIndexPath:(NSIndexPath *)indexPath{
    //通過協議得到cell的間隙
    UIEdgeInsets edgeInsets = [self.delegate collectionView:self.collectionView layout:self insetForSectionAtIndex:indexPath.row];
    CGSize itemSize = [self.delegate collectionView:self.collectionView layout:self sizeForItemAtIndexPath:indexPath];
    float col = 0;
    float shortHeight = [[_colArr objectAtIndex:col] floatValue];

    //找出高度最小的列,將cell加到最小列中
    for (int i = 0; i < _colArr.count; i++) {//遍歷每列
        float height = [[_colArr objectAtIndex:i] floatValue];
        if (height < shortHeight) {
            shortHeight = height;
            col = i;
        }
    }

//在上步的基礎上已經找出第col列高度最小 得到top值
    float top = [[_colArr objectAtIndex:col] floatValue];

    //確定cell的frame
    CGRect frame = CGRectMake(edgeInsets.left + col * (edgeInsets.left + itemSize.width), top + edgeInsets.top, itemSize.width, itemSize.height);

    //更新列高
    [_colArr replaceObjectAtIndex:col withObject:[NSNumber numberWithFloat:top + edgeInsets.top + itemSize.height]];

    //每個cell的frame對應一個indexPath,放入字典中
    [_attributeDict setObject:indexPath forKey:NSStringFromCGRect(frame)];
}

為每一個cell布局完畢后,我們需要實現一個方法,傳入cell的frame信息,返回的是cell的信息. 傳入當前可見cell的rect,視圖進行滑動時候回調

- (NSArray *)indexPathsOfItem:(CGRect)rect{
    //遍歷布局字典通過CGRectIntersectsRect方法確定每個cell的rect與傳入的rect是否有交集,如果結果為true,則此cell應該顯示,將布局字典中對應的indexPath加入數組
    NSMutableArray *array = [NSMutableArray array];
    for (NSString *rectStr in _attributeDict) {//每個cell的frame對應一個indexPath,放入在字典_attributeDict中
        CGRect cellRect = CGRectFromString(rectStr);
        if (CGRectIntersectsRect(cellRect, rect)) {
            NSIndexPath *indexPath = _attributeDict[rectStr];
            [array addObject:indexPath];
        }
    }
    return array;
}

我們需要實現layoutAttributesForElementsInRect: 來返回cell的布局信息
如果忽略傳入的rect一次性將所有的cell布局信息返回,圖片過多時性能會很差

-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
    NSMutableArray *muArr = [NSMutableArray array];
    //indexPathsOfItem方法,根據傳入的frame值計算當前應該顯示的cell
    NSArray *indexPaths = [self indexPathsOfItem:rect];
    for (NSIndexPath *indexPath in indexPaths) {
        UICollectionViewLayoutAttributes *attribute = [self layoutAttributesForItemAtIndexPath:indexPath];
        [muArr addObject:attribute];
    }
    return muArr;
}

最后需要實現collectionViewContentSize方法 來得到collectionView的內容視圖的大小信息
高度在前面的操作中都已經有了結果,我們只需要遍歷前面創建的存放列高的數組得到列最高的一個作為高度返回就可以了

- (CGSize)collectionViewContentSize{
    CGSize size = self.collectionView.frame.size;
    float maxHeight = [[_colArr objectAtIndex:0] floatValue];
    //查找最高的列的高度
    for (int i = 0; i < _colArr.count; i++) {
        float colHeight = [[_colArr objectAtIndex:i] floatValue];
        if (colHeight > maxHeight) {
            maxHeight = colHeight;
        }
    }
    size.height = maxHeight;
    return size;
}

接下來我們在ViewController上聲明一個collectionView并初始化同時ViewController遵守UICollectionViewDelegateFlowLayout和UICollectionViewDataSource協議

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UICollectionViewDelegateFlowLayout,UICollectionViewDataSource>
@property (nonatomic, strong) UICollectionView *collectionView;
@end

.m中導入頭文件

#import "WaterFallCollectionViewCell.h"
#import "WaterFallFlowLayout.h"

懶加載創建存儲圖片的數組

//懶加載
- (NSArray *)imgArr{
    if (!_imgArr) {
        NSMutableArray *muArr = [NSMutableArray array];
        for (int i = 1; i < kImgCount; i++) {
            UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"huoying%d",i]];
            [muArr addObject:image];
        }
        _imgArr = muArr;
    }
    return _imgArr;
}

在viewDidLoad中

 WaterFallFlowLayout *flowLayout = [[WaterFallFlowLayout alloc] init];
    self.collectionView = [[UICollectionView alloc] initWithFrame:[UIScreen mainScreen].bounds collectionViewLayout:flowLayout];
    self.collectionView.backgroundColor = [UIColor yellowColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    //注冊單元格
    [self.collectionView registerClass:[WaterFallCollectionViewCell class] forCellWithReuseIdentifier:identifier];
    [self.view addSubview:self.collectionView];

UICollectionView dataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.imgArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    WaterFallCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    if (!cell) {
        cell = [[WaterFallCollectionViewCell alloc] init];
    }
    cell.image = self.imgArr[indexPath.item];
    return cell;
}
- (float)imgHeight:(float)height width:(float)width{
    /*
        高度/寬度 = 壓縮后高度/壓縮后寬度(100)
     */
    float newHeight = height / width * 100;
    return newHeight;
}
#pragma mark - UICollectionView delegate flowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    UIImage *image = self.imgArr[indexPath.item];
    float height = [self imgHeight:image.size.height width:image.size.width];
    return CGSizeMake(100, height);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    UIEdgeInsets edgeInsets = {5,5,5,5};
    return edgeInsets;
}

運行以上程序我肯可以看到結果:


最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,923評論 6 535
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,740評論 3 420
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,856評論 0 380
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,175評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,931評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,321評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,383評論 3 443
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,533評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,082評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,891評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,067評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,618評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,319評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,732評論 0 27
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,987評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,794評論 3 394
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,076評論 2 375

推薦閱讀更多精彩內容