瀑布流效果使用的是 UICollectionView
根普通的collection view 一樣進行初始化,里面需要計算每一個cell frame屬性
第一個需要知道整個 collectionView 高度
自定義 UICollectionViewLayout,重寫父類的?
-(CGSize)collectionViewContentSize
代碼:
這里瀑布流是兩排,left ?和right,所以要計算左邊 還是右邊圖片的整個高度。
循環(huán)每一個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 可以得到,寬度固定,高度也固定,
現(xiàn)在只要計算她們的center
center 知道x的位置,y的位置未知,
y的位置計算:知道當前的cell的indexPath,可以計算出他上面的cell (左邊和右邊)高度
所以用個for循環(huán),循環(huán)到當前index path
現(xiàn)在 x,y知道,也就知道cell的frame。
UICollectionViewLayoutAttributes *arr=[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
CGFloat cellHeight=[_dataArray[indexPath.row]imgHight];
CGFloat left=0.0;
CGFloat right=0.0;
//? ? 循環(huán)到當前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;