如何 布局一个collectionView瀑布流

ios UICollectionView实现瀑布流 

通过自定义collectionViewCell和重写collectionViewLayout

一.自定义UICollectionViewCell

如>#import@interfaceCollectionCell : UICollectionViewCell

@property (strong, nonatomic)  UIImageView*imageView;

@property (strong, nonatomic)  UIImageView*bottomBar;

@property (strong, nonatomic) CBAutoScrollLabel*productNameLbl;

@property (strong, nonatomic) UILabel*priceLbl;@end////CollectionCell.m//CollectionView////Created by Piosa on 14-6-13.//Copyright (c) 2014年 D2space. All rights reserved.//#import"CollectionCell.h"@implementationCollectionCell- (id)initWithFrame:(CGRect)frame{self=[super initWithFrame:frame];if(self){self.imageView=[[UIImageView alloc]init];[selfaddSubview:self.imageView];//--------------//透明栏//--------------floath=30;floatx=0;floatw=CGRectGetWidth(frame);floaty=0;self.bottomBar=[[UIImageView alloc]initWithFrame:CGRectMake(x, y, w, h)];[selfaddSubview:self.bottomBar];self.bottomBar.image=[UIImage imageNamed:@"toumingse.png"];//产品名y=0;floattempH=h/2;x=3;self.productNameLbl=[[CBAutoScrollLabel alloc]initWithFrame:CGRectMake(x, y, w, tempH)];self.productNameLbl.backgroundColor=[UIColor clearColor];[self.bottomBar addSubview:self.productNameLbl];//产品价格y+=tempH;self.priceLbl=[[UILabel alloc]initWithFrame:CGRectMake(x, y, w, tempH)];self.priceLbl.textColor=[UIColor whiteColor];self.priceLbl.backgroundColor=[UIColor clearColor];self. priceLbl.font=[UIFont systemFontOfSize:12];[self.bottomBar addSubview:self.priceLbl];}returnself;}@end二.创建自定义布局#import#pragmamark WaterF@protocolWaterFLayoutDelegate @required- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath;

@optional- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout heightForHeaderInSection:(NSInteger)section;- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout heightForFooterInSection:(NSInteger)section;@end@interfaceMyLayout : UICollectionViewLayout{floatx;floatleftY;floatrightY;

}

@propertyfloatitemWidth;@property (nonatomic, assign) CGPoint center;@property (nonatomic, assign) CGFloat radius;@property (nonatomic, assign) NSInteger cellCount;///The delegate will point to collection view's delegate automatically.@property (nonatomic, weak)iddelegate;///Array to store attributes for all items includes headers, cells, and footers@property (nonatomic, strong) NSMutableArray*allItemAttributes;@property (nonatomic, assign) UIEdgeInsets sectionInset;@end#import"MyLayout.h"#defineITEM_SIZE 70@implementationMyLayout-(void)prepareLayout{[super prepareLayout];self.itemWidth=150;self.sectionInset=UIEdgeInsetsMake(5,5,5,5);self.delegate= (id )self.collectionView.delegate;CGSize size=self.collectionView.frame.size;_cellCount= [[selfcollectionView] numberOfItemsInSection:0];_center= CGPointMake(size.width /2.0, size.height /2.0);_radius= MIN(size.width, size.height) /2.5;

}-(CGSize)collectionViewContentSize{returnCGSizeMake(320, (leftY>rightY?leftY:rightY));

}- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath  withIndex:(int)index{CGSize itemSize= [self.delegatecollectionView:self.collectionView layout:selfsizeForItemAtIndexPath:indexPath];CGFloat itemHeight= floorf(itemSize.height *self.itemWidth /itemSize.width);UICollectionViewLayoutAttributes*attributes =[UICollectionViewLayoutAttributeslayoutAttributesForCellWithIndexPath:indexPath];index+=1;if(index%2==0){x+=(self.itemWidth+self.sectionInset.left);rightY+=self.sectionInset.top;attributes.frame=CGRectMake(x, rightY,self.itemWidth, itemHeight);rightY+=itemHeight;}else{x=self.sectionInset.left;leftY+=self.sectionInset.top;attributes.frame=CGRectMake(x, leftY,self.itemWidth, itemHeight);leftY+=itemHeight;}returnattributes;

}-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect{x=0;leftY=0;rightY=0;NSMutableArray* attributes =[NSMutableArrayarray];NSLog(@"cellCount=%d",self.cellCount);for(NSInteger i=0; i

}- (UICollectionViewLayoutAttributes *)initialLayoutAttributesForInsertedItemAtIndexPath:(NSIndexPath*)itemIndexPath{UICollectionViewLayoutAttributes* attributes =[selflayoutAttributesForItemAtIndexPath:itemIndexPath];attributes.alpha=0.0;attributes.center=CGPointMake(_center.x, _center.y);returnattributes;

}- (UICollectionViewLayoutAttributes *)finalLayoutAttributesForDeletedItemAtIndexPath:(NSIndexPath*)itemIndexPath{UICollectionViewLayoutAttributes* attributes =[selflayoutAttributesForItemAtIndexPath:itemIndexPath];attributes.alpha=0.0;attributes.center=CGPointMake(_center.x, _center.y);attributes.transform3D= CATransform3DMakeScale(0.1,0.1,1.0);returnattributes;

}@end三.创建UICollectionView用之前自定义的布局进行初始化并注册之前自定义的UICollectionViewCell,参照如下1.创建变量

@property (strong, nonatomic)  UICollectionView*collectionView;2.初始化

MyLayout*layout=[[MyLayout alloc]init];collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0,0, CGRectGetWidth(self.frame),CGRectGetHeight(self.frame)) collectionViewLayout:layout];collectionView.delegate=self;collectionView.dataSource=self;collectionView.scrollEnabled=YES;[selfaddSubview:collectionView];collectionView.backgroundColor=[UIColor clearColor];[collectionView registerClass:[CollectionCellclass] forCellWithReuseIdentifier:@"CollectionCell"];3.实现代理#pragma-mark UICollectionView delegate//根据传入的图片得到宽高-(CGSize)getImgSize:(UIImage *)image{//得到比例floatrate=(itemWidth/image.size.width);returnCGSizeMake(itemWidth, (image.size.height*rate));

}//定义每个UICollectionView 的大小- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{NSDictionary*item=productList[indexPath.row];return[selfgetImgSize:[item objectForKey:KEY_PRODUCT_IMG]];}//定义每个UICollectionView 的 margin-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{returnUIEdgeInsetsMake(5,5,5,5);

}-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{NSLog(@"indexPath=%d",indexPath.row);NSDictionary*item=productList[indexPath.row];DetailViewController*detailView=[[DetailViewController alloc]init];detailView.productID=[[item objectForKey:PRODUCT_ID] integerValue];[viewController.navigationController pushViewController:detailView animated:YES]; }//每个section的item个数-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{returnproductList.count;

}-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionViews cellForItemAtIndexPath:(NSIndexPath*)indexPath{CollectionCell*cell = (CollectionCell *)[collectionViewsdequeueReusableCellWithReuseIdentifier:@"CollectionCell"forIndexPath:indexPath];cell.backgroundColor=[UIColor clearColor];//图片名称//NSString *imageToLoad = [NSString stringWithFormat:@"%d.png", indexPath.row];NSDictionary*item=productList[indexPath.row];NSString*productName;NSString*productImgUrl;if([dataTypeps isEqualToString:TYPE_HISTORY]){NSArray*temp=[[item objectForKey:PRODUCT_NAME] componentsSeparatedByString:@":"];productName=temp[0];}else{productName=[item objectForKey:PRODUCT_NAME];}UIImage*img=[item objectForKey:KEY_PRODUCT_IMG];CGSize size=[selfgetImgSize:img];//加载图片cell.imageView.image=img;cell.imageView.frame=CGRectMake(0,0, size.width, size.height);//--------------//透明栏//--------------floath=30;floatx=0;floatw=size.width;floaty=size.height-h;cell.bottomBar.frame=CGRectMake(x, y, w, h);cell.bottomBar.backgroundColor=[UIColor clearColor];//产品名y=0;floattempH=h/2;x=3;cell.productNameLbl.frame=CGRectMake(x, y, w, tempH);cell.productNameLbl.backgroundColor=[UIColor clearColor];[commonUtil setScrollLabel:cell.productNameLbl withText:productName withCenter:UITextAlignmentLeftwithFontSize:14withTextColor:[UIColor whiteColor]];//产品价格y+=tempH;cell.priceLbl.frame=CGRectMake(x, y, w, tempH);cell.priceLbl.text=[NSString stringWithFormat:@"¥%@",[item objectForKey:PRODUCT_PRICE]];returncell;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,200评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,526评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,321评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,601评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,446评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,345评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,753评论 3 387
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,405评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,712评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,743评论 2 314
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,529评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,369评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,770评论 3 300
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,026评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,301评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,732评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,927评论 2 336

推荐阅读更多精彩内容