iOS开发--瀑布流的简单实现方法之一

作者: 见哥哥长高了 | 来源:发表于2016-06-01 20:01 被阅读902次

瀑布流就是我们经常看到的参差不齐的多栏布局,这种布局出现在国内外大大小小的网站上,很多移动端的页面布局也都选择了这种方式,随意的页面布局却得到不随意的效果,增强了很好的用户体验. 这种布局适合于小数据块,每个数据块内容相近且没有侧重。通常,随着页面滚动条向下滚动,这种布局还会不断加载数据块并附加至当前尾部。
实现瀑布流的方式有很多,我们今天就简单的介绍一种利用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;
}

运行以上程序我肯可以看到结果:


相关文章

  • iOS开发--瀑布流的简单实现方法之一

    瀑布流就是我们经常看到的参差不齐的多栏布局,这种布局出现在国内外大大小小的网站上,很多移动端的页面布局也都选择了这...

  • iOS瀑布流

    最新研究了下iOS中瀑布流的实现方法,一般瀑布流都采用ScrollView + UITableView,或者是使用...

  • iOS - 瀑布流简单的实现

    前言 平时没事也喜欢逛一些技术网站,而瀑布流因为其炫酷的视觉效果(其实就是模仿)和样式使其成为ios当中比较火热的...

  • iOS使用UICollectionView实现瀑布流

    UICollectionView实现瀑布流 在iOS中可以实现瀑布流的目前已知的有2种方案: 使用UIScroll...

  • 简单瀑布流的实现

    简单瀑布流的实现

  • 瀑布流的简单实现方法

    前言 超简单的瀑布流实现,这里说一下笔者的思路,详细代码在这里。 效果演示 实现思路 collectionView...

  • UICollectionViewLayout之瀑布流

    原帖子:华山论剑之浅谈iOS瀑布流 我是模仿上面的代码自己写了一份,实现的是简单的瀑布流:就是把UICollect...

  • 关于自定义瀑布流的布局(Swift)

    瀑布流 UICollectionView Swift 最近整理以前iOS开发中用到的功能代码,发觉对瀑布流的布局有...

  • iOS之简单瀑布流的实现

    前言 超简单的瀑布流实现,这里说一下笔者的思路,详细代码在这里 效果演示 实现思路 collectionView能...

  • iOS瀑布流

    瀑布流 因为iOS提供UICollectionViewLayout的布局类不能实现瀑布流的效果,所以需要自定义一个...

网友评论

    本文标题:iOS开发--瀑布流的简单实现方法之一

    本文链接:https://www.haomeiwen.com/subject/fabhdttx.html