iOS菜鸟开发 CollectionViewCell 的 具体使用步骤

1、确定CollectionViewCell 上要显示的内容,通常是图片(imageView)和文字(label 或者 text)

2、创建 CollectionViewCell 继承 UICollectionViewCell

3、在.m 文件夹里 定义 imageView  和 label,imageView和label 作为一个整体,放在另一个 imageView上

 ①、  UIImageView *imageView = [ [UIImageView alloc] init ];

        imageView.backgroundColor = [UIColor blueColor];

        [self.contentView addSubview:imageView];

        self.imageView = imageView;

  

        UIImageView *iconView = [ [UIImageView alloc] init ];

        iconView.backgroundColor = [UIColor redColor];

        [imageView addSubview:iconView];

         self.iconView = iconView;

 

        UILabel *label = [ [UILabel alloc] init];

        label.text = @"测试";

        label.font = [UIFont systemFontSize:15];

        [imageView addSubview:label];

        self.label = label;

4、 布局 iconView 和 label 在 imageView 上 的位置

- (void)layoutSubviews

{

      [super layoutSubviews];

}

在 cell 要显示的 控制器上需要完成的代码  CollectionView的数据源和代理

@interface ViewController () <UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;

@end

5、cell 在整个页面上的布局

 

6、#pragma mark -- UICollectionViewDataSource--- 数据源

①、定义展示 的 UICollectionCell 的个数

  1. -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section  
  2. {  
  3.     return 30;  
  4. }  

②、定义展示的 Section 的个数

  1. -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView  
  2. {  
  3.     return 1;  
  4. }  

③、每个cell 展示的内容

  1. -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath  
  2. {  
  3.     static NSString * CellIdentifier = @"GradientCell";  
  4.     UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];  
  5.   
  6.     cell.backgroundColor = [UIColor colorWithRed:((10 * indexPath.row) / 255.0) green:((20 * indexPath.row)/255.0) blue:((30 * indexPath.row)/255.0) alpha:1.0f];  
  7.     return cell;  
  8. }  

7、#pragma mark --UICollectionViewDelegate--- 代理

 ①、UICollectionView被选中时调用的方法  

  1. -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath  
  2. {  
  3.     UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];  
  4.     cell.backgroundColor = [UIColor whiteColor];  
  5. }  

 ②、返回这个UICollectionView是否可以被选择

  1. -(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath  
  2. {  
  3.     return YES;  
  4. }  

 

posted @ 2016-01-25 14:21  悠扬007  阅读(319)  评论(0编辑  收藏  举报