UICollectionView 使用

最近看到有人在网上问有关UICollectionView的用法

我总结了一点,希望对初学者有用

UICollectionView 使用步骤

1.添加 UICollectionView 控件

2.布局 UICollectionViewCell

3.设置 UICollectionView的数据源 dataSource

4.实现 UICollectionView的数据源方法  

5. 注册cell关键一

@interface ViewController ()

//1. 连线storyboard 获得  UICollectionView 对象

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

//2.设置数据源

self.collectionView.dataSource = self;


//3.将collectionView添加到View  

[self.view addSubview:collectionView];

}

#pragma mark -- . 数据源方法的实现

//返回有多少组

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionV iew *)collectionView{

//这里返回一组,如果是返回的多组,要用点语法,加属性,来计算

return 1;

}

//返回每组有多少 cell

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{

//这里返回的是有20个cell,如果是其余的,要根据具体情况,具体计算

return self.xxx.count;

}

//返回 每个 cell显示的是什么内容

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{

//1.注册ID

static NSString *ID = @"cell";

//2.获取可重用的cell 如果没有就自己创建 一个返回  :

UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];

//3.设置cell 背景

cell.backgroundColor = [UIColor redColor];

//返回cell

return cell;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容