[OC] UIcollectionView 与 UIcollectionViewCell 的使用

  UICollectionView

  

@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) UICollectionView *collectionView;

@end

//collectionView布局初始化
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
_collectionView = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:flowLayout];
//定义每个Cell 的大小
flowLayout.itemSize = CGSizeMake(280, 280);
//头部大小
flowLayout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 40);
//定义每个Cell 纵向的间距
flowLayout.minimumLineSpacing = 10;
//定义每个Cell 横向的间距
flowLayout.minimumInteritemSpacing = 20;
//定义每个Cell到容器边缘 的边距
flowLayout.sectionInset = UIEdgeInsetsMake(20, 20, 20, 20);//上左下右
    
//collectionView初始化
_collectionView = [[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:flowLayout];
//注册cell
[_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
//设置代理
_collectionView.delegate = self;
_collectionView.dataSource = self;
//背景颜色
_collectionView.backgroundColor = [UIColor greenColor];
//自适应大小
_collectionView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
//界面添加
[self.view addSubview:_collectionView];
//尺寸设置
[_collectionView setFrame:self.view.frame];
//定义展示的UICollectionViewCell的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 1;
}

//每个cell展示的内容的具体实现
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //注意单元格复用,注意identifier和之前注册时用的相同(@"cell")
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[UICollectionViewCell alloc] init];
    }
    return cell;
}

//cell被选中时触发
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"你点了一个单元格");
}

 

新建的UIcoolectionViewCell文件中放入这一句进行初始化:

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self)
    {
        //在这里写入对cell进行定制的内容
    }
    return self;
}

 

posted @ 2018-06-21 14:11  Oran  阅读(880)  评论(0编辑  收藏  举报