---难点已经结束---
没有理解的朋友请重点看上边的难点方法.
必须重写的第二个方法
// 2.返回的是, 每个item对应的布局属性
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
return _attributesArray;
}
必须重写的第三个方法
// 3.返回CollectionView的滚动范围
- (CGSize)collectionViewContentSize {
return CGSizeMake(0, _contentHeight);
}
ViewController里边关于CollectionView的创建和协议方法就没什么好说的了.
看下自定义类CustomCollectionViewLayout的创建以及属性的赋值情况:
CustomCollectionViewLayout *layout = [[CustomCollectionViewLayout alloc] init];
layout.numberOfColumns = 2;/**< 在ViewController里设置瀑布流的列数,2列或3列为最佳 */
layout.delegate = self;/**< 指定VC为计算高度协议方法的代理人 */
再看下协议方法的实现部分(在ViewController.m中实现)
- (CGFloat)collectionView:(UICollectionView *)collectionView
layout:(UICollectionViewLayout *)collectionViewLayout
width:(CGFloat)width
heightForItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
UIImage *image = _imagesArray[indexPath.row];
// 根据传过来的宽度来设置一个合适的矩形, 高度设为CGFLOAT_MAX表示以宽度来计算高度
CGRect boundingRect = CGRectMake(0, 0, width, CGFLOAT_MAX);
// 通过系统函数来得到最终的矩形,需要引入头文件
// #import <AVFoundation/AVFoundation.h>
CGRect imageCurrentRect = AVMakeRectWithAspectRatioInsideRect(image.size, boundingRect);
return imageCurrentRect.size.height;
}
总结
到这里呢,在IOS实现瀑布流就算是结束了,有兴趣的朋友可以自己动手试一下,希望本文对大家开发IOS有所帮助。
注:相关教程知识阅读请移步到IOS开发频道。










