iOS项目开发实战——使用UICollectionView实现瀑布流

来源:互联网 发布:mysql安装步骤 编辑:程序博客网 时间:2024/05/21 19:49

     瀑布流是目前比较流行的一种图片显示方式。很多的电商网站都已这样的方式来呈现商品。现在我们来简单实现一下,本案例使用OC实现。

(1)在Images.xcassets中拖入若干张图片。

(2)在ViewController.h中实现如下:

#import <UIKit/UIKit.h>@interface ViewController : UIViewController<UICollectionViewDelegateFlowLayout,UICollectionViewDataSource>@property (nonatomic, strong) UICollectionView *collectionView;@end




(3)在ViewController.m中实现如下:

#import "ViewController.h"#import "WaterFallCollectionViewCell.h"#import "WaterFallFlowLayout.h"CGFloat const kImgCount = 17;static NSString *identifier = @"collectionView";@interface ViewController ()@property (nonatomic, strong) NSArray  *imgArr;@end@implementation ViewController//懒加载- (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;}- (void)viewDidLoad {    [super viewDidLoad];    // Do any additional setup after loading the view, typically from a nib.    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];}#pragma mark - 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;}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}@end




(4)在WaterFallFlowLayout.h中实现如下:

#import <UIKit/UIKit.h>@interface 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的位置信息@end




(5)在WaterFallFlowLayout.m中实现如下:

#import "WaterFallFlowLayout.h"CGFloat const colCount = 3;@implementation WaterFallFlowLayout//准备布局:得到cell的总个数,为每个cell确定自己的位置- (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++) {        [_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]];    }    }//此方法会多次调用,为每个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;        }    }    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布局完毕后,需要实现这个方法, 传入frame,返回的时cell的信息//传入当前可见cell的rect,视图滑动时调用- (NSArray *)indexPathsOfItem:(CGRect)rect{    //遍历布局字典通过CGRectIntersectsRect方法确定每个cell的rect与传入的rect是否有交集,如果结果为true,则此cell应该显示,将布局字典中对应的indexPath加入数组    NSMutableArray *array = [NSMutableArray array];    for (NSString *rectStr in _attributeDict) {        CGRect cellRect = CGRectFromString(rectStr);        if (CGRectIntersectsRect(cellRect, rect)) {            NSIndexPath *indexPath = _attributeDict[rectStr];            [array addObject:indexPath];        }    }    return array;}//返回cell的布局信息,如果忽略传入的rect一次性将所有的cell布局信息返回,图片过多时性能会很差- (NSArray *)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;}//最后还要实现这个方法,返回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;}@end




(6)在WaterFallCollectionViewCell.h中实现如下:

#import <UIKit/UIKit.h>@interface WaterFallCollectionViewCell : UICollectionViewCell@property (nonatomic, strong) UIImage *image;@end




(7)在WaterFallCollectionViewCell.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

(8)运行程序,效果如下:

.


github主页:https://github.com/chenyufeng1991  。欢迎大家访问!

1 0
原创粉丝点击