纯代码写UICollectionView
1.首先创建一个
XJViewController继承自UIViewController
在XJViewController的.m文件中,进行如下操作:
//负责定义视图中,cell的大小,行和列的最小间距,滚动方向,内容与4个边缘的位置关系等等属性
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
//Cell的大小
layout.itemSize = CGSizeMake(80, 80);
//最小列间距
layout.minimumInteritemSpacing = 10;
//最小行间距
layout.minimumLineSpacing = 10;
//滚动方向为横向
layout.scrollDirection = UICollectionViewScrollPositionCenteredHorizontally;
//内容距离屏幕边缘的距离
layout.sectionInset = UIEdgeInsetsMake(154, 30, 154, 30);
//必须要通过注册class方式 实现重用
[collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"MyCell"];
(在集合视图控制器中,只允许使用注册class的方式来实现重用,这一点与UITableView不同)
2.自定义一个
XJCollectionViewCell 继承自 UICollectionViewCell
在.h文件中声名两个属性,一个是textLabel,一个backGroundIV
在.m文件中实现初始化方法:-(instancetype)initWithFrame:(CGRect)frame
然后在XJViewController.m文件中再次注册一个class方式,实现重用
(一个表格视图可以注册不同的cell类型,只需要唯一标识不同就可以了)
[collectionView registerClass:[XJCollectionViewCell class] forCellWithReuseIdentifier:@"XJCell"];
(注意:一定记得 XJCollectionViewCell别写成了UICollectionViewCell,否则运行就崩溃了,找好久啊)
3.需求
cell的行数是偶数 显示带图片的XJCell 奇数显示带红底的MyCell
if (indexPath.row % 2 == 1)
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
cell.backgroundColor = [UIColor redColor];
return cell;
}else
{
XJCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"XJCell" forIndexPath:indexPath];
cell.backGroundIV.image = [UIImage imageNamed:@"icon40"];
return cell;
}