collectionView纯代码使用

来源:互联网 发布:网络棋牌游戏制作 编辑:程序博客网 时间:2024/05/17 02:42

collectionView和tableView最大的不同之处就是需要自定义cell,所以第一步自定义collectionViewCell

1.自定义collection 


//初始化layout
   
UICollectionViewFlowLayout*flowLayout =[[UICollectionViewFlowLayoutalloc]init];
   
// 2.设置每个格子的尺寸
    flowLayout.
itemSize= CGSizeMake(90,90);
   
   
// 3.设置整个collectionView的内边距
   
   
CGFloat paddingY = 20;
   
   
CGFloat paddingX = 20;
   
    flowLayout.
sectionInset= UIEdgeInsetsMake(paddingY, paddingX, paddingY, paddingX);
   
   
// 4.设置每一行之间的间距
    flowLayout.
minimumLineSpacing= paddingY;
//    flowLayout.headerReferenceSize = CGSizeMake(SCREENWIDTH, 50);//设置headerView的尺寸大小
    [flowLayout
setScrollDirection:UICollectionViewScrollDirectionVertical];//设置滚动方向
   
//初始化ConllectionView
   
_commonConllectionView= [[UICollectionViewalloc]initWithFrame:CGRectMake(0,0,SCREENWIDTH,SCREENHEIGHT)collectionViewLayout:flowLayout];
   
//注册单元格
    [
_commonConllectionViewregisterClass:[WCRCommonCollectionViewCellclass]forCellWithReuseIdentifier:@"commonCollectionCell"];
//    _commonConllectionView
    //注册headerView 此处的ReuserIdentifier 必须和 cellForItemAtIndexPath 方法中一致  
    [_commonConllectionView registerClass:[*** class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withTeuseIdentifier @“reuableView”];
   
   
//设置代理
   
_commonConllectionView.delegate= self;
   
_commonConllectionView.dataSource= self;
   
_commonConllectionView.backgroundColor= [UIColorwhiteColor];
    [self.view addSubview:_commonConllectionView];

2.实现3个代理 DataSource,Delegate,DelegateFlowLayout

3.实现代理方法
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView*)collectionView
{
   
return 1;
}

-(
NSInteger)collectionView:(UICollectionView*)collectionView numberOfItemsInSection:(NSInteger)section{
   
return _commonConllectionArray.count;
}

//定义每个UICollectionView的大小
- (
CGSize)collectionView:(UICollectionView*)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath*)indexPath
{
   return CGSizeMake(100,100);
}

-(
UICollectionViewCell*)collectionView:(UICollectionView*)collectionView cellForItemAtIndexPath:(NSIndexPath*)indexPath{
   
    WCRCommonCollectionViewCell *cell = (WCRCommonCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"commonCollectionCell" forIndexPath:indexPath];

    cell.commonInfo= _commonConllectionArray[indexPath.row];
   
return cell;
}

0 0
原创粉丝点击