瀑布流的实现要重写UICollectionViewLayout来实现:主要是重写以下几个方法:
-(void)prepareLayout;//开始布局
-(CGSize)collectionViewContentSize;//内容大小
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect;//每个cell的属性列表
-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath//单个的属性
具体的实现:
@protocol WaterFLayoutDelegate<NSObject>
@required
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath: (NSIndexPath *)indexPath;
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section;
@end
@interface MyLayout :UICollectionViewLayout
{
float x;
float leftY;
float rightY;
}
@property(nonatomic,assign)UIEdgeInsets sectionInset;
@property(nonatomic,weak)id<WaterFLayoutDelegate> delegate;
@end
@implementation MyLayout
-(void)prepareLayout
{
[superprepareLayout];
self.delegate=(id<WaterFLayoutDelegate>)self.collectionView.delegate;
self.sectionInset=[self.delegatecollectionView:self.collectionViewlayout:selfinsetForSectionAtIndex:0];
}
-(CGSize)collectionViewContentSize
{
return CGSizeMake(self.collectionView.frame.size.width,MAX(leftY,rightY));
}
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
x=0;
leftY=0;
rightY=0;
NSMutableArray *attributes=[NSMutableArrayarray];
NSInteger section=self.collectionView.numberOfSections;
for (int i=0; i<section; i++) {
NSInteger allCount=[self.collectionViewnumberOfItemsInSection:i];
for (int j=0; j<allCount; j++) {
NSIndexPath *indexPath=[NSIndexPath indexPathForRow:j inSection:i];
[attributesaddObject:[selflayoutAttributesForItemAtIndexPath:indexPath]];
}
}
return attributes;
}
-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
NSAssert([self.delegaterespondsToSelector:@selector(collectionView:layout:sizeForItemAtIndexPath:)],@"collectionView:layout:sizeForItemAtIndexPath not exist");
CGSize itemSize=[self.delegatecollectionView:self.collectionViewlayout:selfsizeForItemAtIndexPath:indexPath];
UICollectionViewLayoutAttributes *attributes=[UICollectionViewLayoutAttributeslayoutAttributesForCellWithIndexPath:indexPath];
if (leftY<=rightY) {
x=self.sectionInset.left;
leftY+=self.sectionInset.top;
attributes.frame=CGRectMake(x,leftY, itemSize.width,itemSize.height);
leftY+=itemSize.height;
}else{
x=itemSize.width+self.sectionInset.left*3;
rightY+=self.sectionInset.top;
attributes.frame=CGRectMake(x,rightY, itemSize.width, itemSize.height);
rightY+=itemSize.height;
}
return attributes;
}
@end