瀑布流效果

现在随处可见,各种App首页采用瀑布流展示的效果,瀑布流它是一种自定义的布局方式,比如系统的FlowOut流水布局样式,直接上代码

自定义WaterflowLayout类继承UICollectionViewLayout

实现以下4个方法

@interface UICollectionWaterflowLayout : UICollectionViewLayout

/**

* 初始化

*/

- (void)prepareLayout

{

[super prepareLayout];

self.contentHeight = 0;

// 清除以前计算的所有高度

[self.columnHeights removeAllObjects];

for (NSInteger i = 0; i < self.columnCount; i++) {

[self.columnHeights addObject:@(self.edgeInsets.top)];

}

// 清除之前所有的布局属性

[self.attrsArray removeAllObjects];

// 开始创建每一个cell对应的布局属性

NSInteger count = [self.collectionView numberOfItemsInSection:0];

for (NSInteger i = 0; i < count; i++) {

// 创建位置

NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];

// 获取indexPath位置cell对应的布局属性

UICollectionViewLayoutAttributes *attrs = [self layoutAttributesForItemAtIndexPath:indexPath];

[self.attrsArray addObject:attrs];

}

}

/**

* 决定cell的排布

*/

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect

{

return self.attrsArray;

}


/**

* 返回indexPath位置cell对应的布局属性

*/

- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath

{

// 创建布局属性

UICollectionViewLayoutAttributes *attrs = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];

// collectionView的宽度

CGFloat collectionViewW = self.collectionView.frame.size.width;

// 设置布局属性的frame

CGFloat w = (collectionViewW - self.edgeInsets.left - self.edgeInsets.right - (self.columnCount - 1) * self.columnMargin) / self.columnCount;

CGFloat h = [self.delegate waterflowLayout:self heightForItemAtIndex:indexPath.item itemWidth:w];

// 找出高度最短的那一列

NSInteger destColumn = 0;

CGFloat minColumnHeight = [self.columnHeights[0] doubleValue];

for (NSInteger i = 1; i < self.columnCount; i++) {

// 取得第i列的高度

CGFloat columnHeight = [self.columnHeights[i] doubleValue];

if (minColumnHeight > columnHeight) {

minColumnHeight = columnHeight;

destColumn = i;

}

}

CGFloat x = self.edgeInsets.left + destColumn * (w + self.columnMargin);

CGFloat y = minColumnHeight;

if (y != self.edgeInsets.top) {

y += self.rowMargin;

}

attrs.frame = CGRectMake(x, y, w, h);

// 更新最短那列的高度

self.columnHeights[destColumn] = @(CGRectGetMaxY(attrs.frame));

// 记录内容的高度

CGFloat columnHeight = [self.columnHeights[destColumn] doubleValue];

if (self.contentHeight < columnHeight) {

self.contentHeight = columnHeight;

}

return attrs;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容