iOS下瀑布流实现效果以及思路

瀑布流效果使用的是 UICollectionView

根普通的collection view 一样进行初始化,里面需要计算每一个cell frame属性

第一个需要知道整个 collectionView 高度

自定义 UICollectionViewLayout,重写父类的 

-(CGSize)collectionViewContentSize

代码:

这里瀑布流是两排,left  和right,所以要计算左边 还是右边图片的整个高度。

循环每一个cell,求和高度,并返结果

CGFloat left=0.0;

CGFloat right=0.0;

for (int i=0; i<_dataArray.count; i++) {

CGFloat h=[_dataArray[i] imgHight];

if (left<=right) {//左边小于右边就加左边,右边小于左边就加右边

left+=h;

}else{

right+=h;

}

}

整个 collectionView 高度计算好了 ,collectionView知道每一个cell的位置,

也是要重写两个方法

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

分别计算左边cell 和右边每一个cell的,她们的size 可以得到,宽度固定,高度也固定,

现在只要计算她们的center

center 知道x的位置,y的位置未知,

y的位置计算:知道当前的cell的indexPath,可以计算出他上面的cell (左边和右边)高度

所以用个for循环,循环到当前index path

现在 x,y知道,也就知道cell的frame。

UICollectionViewLayoutAttributes *arr=[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];

CGFloat cellHeight=[_dataArray[indexPath.row]imgHight];

CGFloat left=0.0;

CGFloat right=0.0;

//    循环到当前cell,计算出当前indexpath的cell 高度,中心

for (int i=0; i < indexPath.row; i++) {

CGFloat h=[_dataArray[i]imgHight];

if (left<=right) {

left+=h;

}else{

right+=h;

}

}

if (left<=right) {

arr.center=CGPointMake(80, left+cellHeight/2);

}else{

arr.center=CGPointMake(240, right+cellHeight/2);

}

arr.size=CGSizeMake(160, cellHeight);

return arr;


-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect

代码

for (int i=0; i<[self.collectionView numberOfItemsInSection:0]; i++) {

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

[arr addObject:[self layoutAttributesForItemAtIndexPath:indexpath]];

}

return arr;

代码下载



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

相关阅读更多精彩内容

友情链接更多精彩内容