瀑布流就是我們經常看到的參差不齊的多欄布局,這種布局出現在國內外大大小小的網站上,很多移動端的頁面布局也都選擇了這種方式,隨意的頁面布局卻得到不隨意的效果,增強了很好的用戶體驗. 這種布局適合于小數據塊,每個數據塊內容相近且沒有側重。通常,隨著頁面滾動條向下滾動,這種布局還會不斷加載數據塊并附加至當前尾部。
實現瀑布流的方式有很多,我們今天就簡單的介紹一種利用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;
}
運行以上程序我肯可以看到結果: