ViewController.m
#import "ViewController.h"
@interface ViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//每一个collectionView必须有个layout
//layout布局就是collectionView的精华所在
//不同的layout可以布局不同的界面效果
//layout是可以自定义的,系统也给我们提供了常用的子类
//系统提供的UICollectionViewFlowLayout(显示九宫格样式)
//flowLayout可以实际大部分程序的布局需求所以一般都使用这个layout
UICollectionViewFlowLayout *flowLayout=[[UICollectionViewFlowLayout alloc]init];
//设置行间距-最小行间距
flowLayout.minimumLineSpacing=10;
//设置每单元格左右间距
flowLayout.minimumInteritemSpacing=10;
//滑动的方向
flowLayout.scrollDirection=UICollectionViewScrollDirectionVertical;
//设置view的周边间距
flowLayout.sectionInset=UIEdgeInsetsMake(10, 10, 10, 10);
//设置单元格的大小
flowLayout.itemSize=CGSizeMake(50, 50);
//一个layout对象不能同时用在多个collectionView上
//创建collectionView
UICollectionView *collection=[[UICollectionView alloc]initWithFrame:self.view.frame collectionViewLayout:flowLayout];
//设置代理
collection.delegate=self;
//设置数据源
collection.dataSource=self;
//展示
[self.view addSubview:collection];
//注册UICollectionViewCell
[collection registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];
/*
XIB自定义Cell
[collectionView registerNib:[UINib nibWithNibName:@"CustomCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
*/
}
#pragma mark-UICollectionViewDataSource
\- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return 50;
}
- (UICollectionViewCell \*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
\*
XIB自定义Cell
CustomCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
*/
//获取通过标识符获取cell
UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
cell.backgroundColor=[UIColor colorWithRed:arc4random()%255/255.f green:arc4random()%255/255.f blue:arc4random()%255/255.f alpha:1];
return cell;
}
@end
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。