UICollectionView简单使用

UICollectionView的使用方法与UITableView十分类似,布局

使用UICollectionViewController要实现如下三个步骤:spa

// 一.初始化的时候设置布局参数code

// 二.必须collectionView注册cellorm

// 三.自定义cell对象

 

 

1.重写init方法,在init方法中调用initWithCollectionViewLayout这个带布局参数的方法,方便用init方式建立一个UICollectionViewController。blog

2.建立UICollectionViewLayout布局的时候通常用它的子类UICollectionViewFlowLayout来建立一个流水布局。继承

3.设置布局对象的参数:单元格的排列方向,间距,大小图片

 1 -(instancetype)init
 2 {
 3     //流水布局
 4     UICollectionViewFlowLayout* layout=[[UICollectionViewFlowLayout alloc]init];
 5     
 6     //设置纵向排列
 7     layout.scrollDirection=UICollectionViewScrollDirectionHorizontal;
 8     
 9     //设置每一个cell间的距离
10     layout.minimumLineSpacing=0;
11 
12     //设置cell大小
13     layout.itemSize=[UIScreen mainScreen].bounds.size;
14     
15     //初始化一个流水布局的collectController
16     return [self initWithCollectionViewLayout:layout];
17 }

 

1.注册单元格类型ci

2.由于UICollectionViewController的collectionView继承自UIScrollView,因此能够设置它的分页,弹簧效果等属性string

 1 - (void)viewDidLoad {
 2     [super viewDidLoad];
 3     
 4     //注册cell,  WBFeatureCell是自定义UICollectionViewCell
 5     [self.collectionView registerClass:[WBFeatureCell class] forCellWithReuseIdentifier:reuseIdentifier];
 6     
 7     //设置分页
 8     self.collectionView.pagingEnabled=YES;
 9     //设置弹簧效果
10     self.collectionView.bounces=NO;
11     //设置滚动条
12     self.collectionView.showsHorizontalScrollIndicator=NO;
13     
14 }

 

 1 循环利用的标识:  static NSString * const reuseIdentifier = @"Cell";
#pragma mark <UICollectionViewDataSource> 设置数据源方法
 2 /**
 3  *设置分组数量
 4  */
 5 - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
 6   return 1;
 7 }
 8 
 9 
10 /**
11  *设置cell数量
12  */
13 - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
14     return 4;
15 }
16 
17 /**
18  *设置每个cell的内容,这个方法会调用屡次来设置每个cell
19  */
20 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
21     WBFeatureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
22 
23     //加载图片
24     UIImage* img=[UIImage imageNamed: [NSString stringWithFormat:@"new_feature_%@",@(indexPath.row+1)]];
25     cell.image=img;
26   
27     return cell;
28 }

 

自定义cell 的时候要注意把内容加到contentView上面

[self.contentView addSubview:imgView];

相关文章
相关标签/搜索