ios 应用UICollectionView实现瀑布流

本文介绍如何自定义UICollectionView的单元格与布局,包括创建UICollectionViewCell类、定义UICollectionViewLayout子类来实现瀑布流布局,并展示如何在项目中初始化与使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.自定义UICollectionViewCell

如>

#import <UIKit/UIKit.h>


@interface CollectionCell : UICollectionViewCell



@property (strongnonatomic)  UIImageView *imageView;


@property (strongnonatomic)  UIImageView *bottomBar;


@property (strongnonatomicCBAutoScrollLabel *productNameLbl;


@property (strongnonatomicUILabel *priceLbl;


 

@end



//

//  CollectionCell.m

//  CollectionView

//

//  Created by Piosa on 14-6-13.

//  Copyright (c) 2014 D2space. All rights reserved.

//


#import "CollectionCell.h"


@implementation CollectionCell


- (id)initWithFrame:(CGRect)frame

{

    self = [super initWithFrame:frame];

    if (self)

    {

        

        self.imageView=[[UIImageView alloc]init];

        [self addSubview:self.imageView];

        //--------------

        //透明栏

        //--------------

        float h=30;

        float x=0;

        float w=CGRectGetWidth(frame);

        float y=0;

        self.bottomBar=[[UIImageView alloc]initWithFrame:CGRectMake(x, y, w, h)];

        [self addSubview:self.bottomBar];

        self.bottomBar.image=[UIImage imageNamed:@"toumingse.png"];

        

        //产品名

        y=0;

        float tempH=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];

        selfpriceLbl.font=[UIFont systemFontOfSize:12];

        [self.bottomBar addSubview:self.priceLbl]; 

    }

    return self;

}

@end



二.创建自定义布局

 #import <UIKit/UIKit.h>



#pragma mark WaterF

@protocol WaterFLayoutDelegate <UICollectionViewDelegate>

@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



@interface MyLayout : UICollectionViewLayout

{

    float x;

    

    float leftY;

    

    float rightY;

}

@property float itemWidth;


    @property (nonatomicassignCGPoint center;


    @property (nonatomicassignCGFloat radius;


    @property (nonatomicassignNSInteger cellCount;



    /// The delegate will point to collection view's delegate automatically.

    @property (nonatomicweakid <WaterFLayoutDelegate> delegate;


    /// Array to store attributes for all items includes headers, cells, and footers

    @property (nonatomicstrongNSMutableArray *allItemAttributes;




    @property (nonatomicassignUIEdgeInsets sectionInset;


@end



 

#import "MyLayout.h"


#define ITEM_SIZE 70


@implementation MyLayout


-(void)prepareLayout

{

    [super prepareLayout];

    

    self.itemWidth=150;

    

    self.sectionInset=UIEdgeInsetsMake(5555);

    

    self.delegate = (id <WaterFLayoutDelegate> )self.collectionView.delegate;

    

    CGSize size = self.collectionView.frame.size;

    _cellCount = [[self collectionViewnumberOfItemsInSection:0];

    _center = CGPointMake(size.width / 2.0, size.height / 2.0);

    _radius = MIN(size.width, size.height) / 2.5;

}


-(CGSize)collectionViewContentSize

{

    return CGSizeMake(320, (leftY>rightY?leftY:rightY));

}


- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath  withIndex:(int)index

{

     CGSize itemSize = [self.delegate collectionView: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(xrightYself.itemWidth, itemHeight);

        rightY+=itemHeight;

        

    }else

    {

        x=self.sectionInset.left;

        leftY+=self.sectionInset.top;

        attributes.frame = CGRectMake(xleftYself.itemWidth, itemHeight);

        leftY+=itemHeight;

        

    }

 

    

    return attributes;

}


-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect

{

    x=0;

    leftY=0;

    rightY=0;

    

    NSMutableArray* attributes = [NSMutableArray array];

    

    NSLog(@"cellCount=%d",self.cellCount);

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

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

        

        [attributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath withIndex:i]];

    }

    return attributes;

}


- (UICollectionViewLayoutAttributes *)initialLayoutAttributesForInsertedItemAtIndexPath:(NSIndexPath*)itemIndexPath

{

    UICollectionViewLayoutAttributes* attributes = [self layoutAttributesForItemAtIndexPath:itemIndexPath];

    attributes.alpha = 0.0;

    attributes.center = CGPointMake(_center.x_center.y);

    return attributes;

}


- (UICollectionViewLayoutAttributes *)finalLayoutAttributesForDeletedItemAtIndexPath:(NSIndexPath*)itemIndexPath

{

    UICollectionViewLayoutAttributes* attributes = [self layoutAttributesForItemAtIndexPath:itemIndexPath];

    attributes.alpha = 0.0;

    attributes.center = CGPointMake(_center.x_center.y);

    attributes.transform3D = CATransform3DMakeScale(0.10.11.0);

    return attributes;

}




@end


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


1.创建变量

@property (strong,nonatomic)  UICollectionView *collectionView;

2.初始化 

 MyLayout *layout=[[MyLayout alloc]init];

    

    collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(00CGRectGetWidth(self.frame),CGRectGetHeight(self.frame)) collectionViewLayout:layout];


    collectionView.delegate=self;

    

    collectionView.dataSource=self;

    

    collectionView.scrollEnabled=YES;

    

    [self addSubview:collectionView];

    

    collectionView.backgroundColor=[UIColor clearColor];

    

    [collectionView registerClass:[CollectionCell classforCellWithReuseIdentifier:@"CollectionCell"];


3.实现代理

<UICollectionViewDelegate,UICollectionViewDataSource>


#pragma -mark UICollectionView delegate


//根据传入的图片得到宽高

-(CGSize)getImgSize:(UIImage *)image

{

    //得到比例

    

    float rate=(itemWidth/image.size.width);

    

    return CGSizeMake(itemWidth, (image.size.height*rate));

}




//定义每个UICollectionView 的大小

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath

{

    

    NSDictionary *item=productList[indexPath.row];

  

    

    return [self getImgSize:[item objectForKey:KEY_PRODUCT_IMG]];

}


//定义每个UICollectionView  margin

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section

{

    return UIEdgeInsetsMake(5555);

}




-(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_IDintegerValue];

    

    [viewController.navigationController pushViewController:detailView animated:YES];

    

    

}


//每个sectionitem个数

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section

{

    return productList.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_NAMEcomponentsSeparatedByString:@":"];

        productName=temp[0];

    }else

    {

        productName=[item objectForKey:PRODUCT_NAME];

    }

    

    

    

    UIImage *img=[item objectForKey:KEY_PRODUCT_IMG];

    

    

    CGSize size=[self getImgSize:img];

    

    //加载图片

    cell.imageView.image = img;

    

    cell.imageView.frame=CGRectMake(00, size.width, size.height);

    

    

  

     //--------------

    //透明栏

    //--------------

    float h=30;

    float x=0;

    float w=size.width;

    float y=size.height-h;

    

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

    

    cell.bottomBar.backgroundColor=[UIColor clearColor];

    

 

    //产品名

    y=0;

    float tempH=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:14 withTextColor:[UIColor whiteColor]];

 

    

    //产品价格

    y+=tempH;

    

    cell.priceLbl.frame=CGRectMake(x, y, w, tempH);

    

    

    cell.priceLbl.text=[NSString stringWithFormat:@"%@",[item objectForKey:PRODUCT_PRICE]];

 

    

    return cell;

}



四.实现效果
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值