UICollectionView 简单实用

来源:互联网 发布:使用vmware安装linux 编辑:程序博客网 时间:2024/06/04 19:31

UICollectionView 实现有2种方式,第一种是纯代码,第二种就是storyBoard 实现,

纯代码实现

初始化

    //初始化layout布局    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];    //设置header的大小,另一个方法也可以设置,选其一    layout.headerReferenceSize=CGSizeMake(collectionWith, 100);    //设置滚动模式    [layout setScrollDirection:UICollectionViewScrollDirectionVertical];    //初始化UICollectionView    _collectionView=[[UICollectionView alloc]initWithFrame:CGRectMake(0,0, ScreenWidth, ScreenHeight) collectionViewLayout:layout];    _collectionView.delegate = self;    _collectionView.dataSource = self;    //注册自定义的collectionViewCell,    [_collectionView registerClass:[zanCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];    //注册自定义的collectionViewHeader,        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];    //**如果这快的cell 不是纯代码写的,而是用xib 画的,注册的方式改为    //    UINib* nib = [UINib nibWithNibName:@"NormalProductCollectionViewCell" bundle:nil];  //      [_collectionView registerNib:nib forCellWithReuseIdentifier:@"IDNormalProductCollectionViewCell"];//    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"reusableView"];    [self.view addSubview:_collectionView];

实现方法

#pragma mark - UICollectionViewDataSource//每个section的item个数- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{    return 9;}/**而如果我们在TableView向数据源请求数据之前使用-registerNib:forCellReuseIdentifier:方法为@“MY_CELL_ID”注册过nib的话,就可以省下每次判断并初始化cell的代码,要是在重用队列里没有可用的cell的话,runtime将自动帮我们生成并初始化一个可用的cell。这个特性很受欢迎,因此在UICollectionView中Apple继承使用了这个特性,并且把其进行了一些扩展。使用以下方法进行注册:-registerClass:forCellWithReuseIdentifier:-registerClass:forSupplementaryViewOfKind:withReuseIdentifier:-registerNib:forCellWithReuseIdentifier:-registerNib:forSupplementaryViewOfKind:withReuseIdentifier:相比UITableView有两个主要变化:一是加入了对某个Class的注册,这样即使不用提供nib而是用代码生成的view也可以被接受为cell了;二是不仅只是cell,Supplementary View也可以用注册的方法绑定初始化了。在对collection view的重用ID注册后,就可以像UITableView那样简单的写cell配置了:**/- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{    zanCollectionViewCell *cell = (zanCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];    return cell;}-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView*)collectionView{    return 1;}#pragma mark -UICollectionViewDelegateFlowLayout//设置每个item的尺寸- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{    return CGSizeMake(collectionWith, 100);}//设置每个item的UIEdgeInsets- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{    return UIEdgeInsetsMake(0,0,0,0);}//设置每个item水平间距- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{    return 0;}//设置每个item垂直间距- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{    return 0;}//这可以设置headerview 的宽高- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{        return CGSizeMake(ScreenWidth, 100);}//通过设置SupplementaryViewOfKind 来设置头部或者底部的view,其中 ReuseIdentifier 的值必须和 注册是填写的一致,本例都为 “header”- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{    UICollectionReusableView* headerView = nil;    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {        headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];        headerView.backgroundColor=[UIColor orangeColor];        UIImageView *imageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, 100)];        imageView.image=[UIImage imageNamed:@"chatBar_faceSelected"];        [headerView addSubview:imageView];        return headerView;    }    return nil;}#pragma mark -UICollectionViewDelegate//点击item方法- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{//    MyCollectionViewCell *cell = (MyCollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];//    NSString *msg = cell.botlabel.text;//    NSLog(@"%@",msg);}//当前ite是否可以点击- (BOOL) collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(nonnull NSIndexPath *)indexPath{    if (indexPath.row % 2)    {        return YES;    }    return NO;}//我们也可以通过设置UICollectionViewCell的selectedBackgroundView属性来改变cell选中时的背景视图。 //我们还可以设置哪些cell点击时不高亮,点击时cell的样式和点击后cell的样式- (BOOL)collectionView:(UICollectionView *)collectionView shouldHighlightItemAtIndexPath:(NSIndexPath *)indexPath{    return YES;}- (void)collectionView:(UICollectionView *)collectionView didHighlightItemAtIndexPath:(NSIndexPath *)indexPath{    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];    cell.backgroundColor = [UIColor redColor];}- (void)collectionView:(UICollectionView *)collectionView didUnhighlightItemAtIndexPath:(NSIndexPath *)indexPath{    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];    cell.backgroundColor = [UIColor grayColor];}

上面就是纯代码实现collectionView的方法
下面用StoryBoard实现
首先拖一个cellectionView 到sb中,然后设置delegate,datasource,设置他的宽高,
间距等一系列坐标都可以在sb设置
这里写图片描述

然后代码实现一些方法,具体代码和上面的一样,sb 和纯代码写的区别,就是初始化,cellectionview 和cell的区别的,别的方面差不多都一样;

对于cell的重用,现在的代码不需要写if(cell==nil) 这种形式了,因为在初始化的时候,registerXXX,这种方式,或者在sb里面自带的cell已经实现了重用,但是cellfor 的方法里面必须要实用唯一的注册ID
like

    MyCell*cell=[cvdequeueReusableCellWithReuseIdentifier:@”MY_CELL_ID”];

这样就实现了省去不必要的代码了;

对于高度的计算
ios7简单的估算cell 的高度根据文字的长度计算高度,

//获得文字宽高+(CGSize)getLabelSize:(NSString*)lbtext             withFont:(UIFont*)font         withRowWidth:(float)width{    NSDictionary *attribute = @{NSFontAttributeName:font};    CGSize labelsize ;//= [lbtext sizeWithFont:font constrainedToSize:CGSizeMake(width, constrainedHeight) lineBreakMode:UILineBreakModeWordWrap];    if (IOS7_OR_LATER) {        labelsize= [lbtext boundingRectWithSize:CGSizeMake(width, MAXFLOAT)                                        options: NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesLineFragmentOrigin |NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;    }else{        labelsize = [lbtext sizeWithFont:font constrainedToSize:CGSizeMake(width, MAXFLOAT) lineBreakMode:NSLineBreakByWordWrapping];    }    return labelsize;}

这些都是简单的计算高度,对于复杂的cell 的高度计算这样计算还是会有点卡顿的现象
推荐第三方的优秀的计算方法
http://blog.sunnyxx.com/2015/05/17/cell-height-calculation/

以上就是简单的collectionview的使用,tableview 基本上类似,谢谢,如果不对,还让指正;

参考
http://onevcat.com/2012/06/introducing-collection-views/

0 0
原创粉丝点击