自定义的瀑布流
1.创建自定义瀑布流
- (void)createView{
// 创建自定义的layOut
CLFlowLayout *flowLayout = [[CLFlowLayout alloc] init];
// 设置四周的边框
flowLayout.edgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
// 设置列数
flowLayout.columnCounts = 2;
// 设置行间距
flowLayout.rowSpace = 10;
// 设置列间距
flowLayout.columnSpace = 10;
// 设置代理人
flowLayout.delegate = self;
UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:flowLayout];
collectionView.dataSource = self;
collectionView.delegate = self;
[self.view addSubview:collectionView];
// cell注册
[collectionView registerClass:[MyCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];
}
2.用来计算item高的协议方法:计算的item的高=原始的height * width / 原始的width
// 用来计算item高的协议方法
- (CGFloat)clFlowLayout:(CLFlowLayout *)flowLayout heightForRowAtIndex:(NSIndexPath *)indexPath width:(CGFloat)width{
// 图片的原始尺寸都保存在model里
// 计算的item高 = 原始的height * width / 原始的width
Picture *pic = self.picArr[indexPath.row];
CGFloat height = [pic.height floatValue] * width / [pic.width floatValue];
return height;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return self.picArr.count;
}
3.collectionView的两个协议方法
4.自定义的cell, 需要重写layoutSubView方法,防止重用之后,还是上一次出现的尺寸,所以为了能显示最新的尺寸,需要重新进行布局
- (void)createView{
self.picImageView = [[UIImageView alloc] initWithFrame:self.contentView.frame];
[self.contentView addSubview:self.picImageView];
}
// 防止重用之后,还是上一次出现的尺寸,所以为了能显示最新的尺寸,需要重新进行布局
- (void)layoutSubviews{
[super layoutSubviews];
// 重新布局cell上的子视图
self.picImageView.frame = self.contentView.frame;
}