天天看點

collectionView純代碼使用

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

1.自定義collection 

// 初始化 layout

    UICollectionViewFlowLayout *flowLayout =[[ UICollectionViewFlowLayout alloc ] 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 = [[ UICollectionView alloc ] initWithFrame : CGRectMake ( 0 , 0 , SCREENWIDTH , SCREENHEIGHT ) collectionViewLayout :flowLayout];

    // 注冊單元格

    [ _commonConllectionView registerClass :[ WCRCommonCollectionViewCell class ] forCellWithReuseIdentifier : @"commonCollectionCell" ]; //    _commonConllectionView     //注冊headerView 此處的ReuserIdentifier 必須和 cellForItemAtIndexPath 方法中一緻       [ _commonConllectionView registerClass:[*** class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withTeuseIdentifier @“reuableView”];    

    // 設定代理

    _commonConllectionView . delegate = self ;

    _commonConllectionView . dataSource = self ;

    _commonConllectionView . backgroundColor = [ UIColor whiteColor ];     [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; }