CHTCollectionViewWaterfallLayout下载链接
layout = [[CHTCollectionViewWaterfallLayout alloc] init];
layout.sectionInset = UIEdgeInsetsMake(0, 5, 5, 5);
layout.columnCount = 2;
layout.minimumInteritemSpacing = 5;
layout.minimumColumnSpacing = 5;
self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, screenWidth, screenHeight-64-10) collectionViewLayout:layout];
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
self.collectionView.backgroundColor = [UIColor whiteColor];
[self.collectionView registerNib:[UINib nibWithNibName:@"WaterViewCell" bundle:nil] forCellWithReuseIdentifier:@"WaterViewCell"];
[_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:CHTCollectionElementKindSectionHeader withReuseIdentifier:MYHeader];
//保持一直可滑动
self.collectionView.alwaysBounceVertical = YES;
[self.view addSubview:self.collectionView];
#pragma mark - UICollectionView Delegate
//获取每组返回几个数据
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return _dataArr.count;
}
//获取返回几组
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
//
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
WaterViewCell *cell = (WaterViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"WaterViewCell"
forIndexPath:indexPath];
if (indexPath.row<_dataArr.count) {
WaterModel *model = [_dataArr objectAtIndex:indexPath.row];
cell.model = model;
//设置图片的高度
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"ls_AdDefaultImage.png"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if (image) {
//宽高比
CGFloat x = image.size.width/image.size.height;
CGFloat cellHeight = ((screenWidth-30)/2)/x;
if (cell.model.imageSize.height!=cellHeight) {
model.imageSize = CGSizeMake((screenWidth-30)/2, cellHeight);
//刷新时不让屏幕闪光
[UIView performWithoutAnimation:^{
[_collectionView reloadSections:[NSIndexSet indexSetWithIndex:0]];
}];
}
}
}];
}
return cell;
}
#pragma mark - CHTCollectionViewDelegateWaterfallLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
if (indexPath.row<_dataArr.count) {
WaterModel *model = [_dataArr objectAtIndex:indexPath.row];
if (model.imageSize.height!=0) {
return model.imageSize;
}
return CGSizeMake((screenWidth-30)/2, 0);
}
return CGSizeZero;
}