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 的个数
- -(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
- {
- return 30;
- }
②、定义展示的 Section 的个数
- -(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
- {
- return 1;
- }
③、每个cell 展示的内容
- -(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
- {
- static NSString * CellIdentifier = @"GradientCell";
- UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
- cell.backgroundColor = [UIColor colorWithRed:((10 * indexPath.row) / 255.0) green:((20 * indexPath.row)/255.0) blue:((30 * indexPath.row)/255.0) alpha:1.0f];
- return cell;
- }
7、#pragma mark --UICollectionViewDelegate--- 代理
①、UICollectionView被选中时调用的方法
- -(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
- {
- UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
- cell.backgroundColor = [UIColor whiteColor];
- }
②、返回这个UICollectionView是否可以被选择
- -(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
- {
- return YES;
- }