最近看到有人在網(wǎng)上問有關(guān)UICollectionView的用法
我總結(jié)了一點,希望對初學者有用
UICollectionView 使用步驟
1.添加 UICollectionView 控件
2.布局 UICollectionViewCell
3.設(shè)置 UICollectionView的數(shù)據(jù)源 dataSource
4.實現(xiàn) UICollectionView的數(shù)據(jù)源方法 ?
5. 注冊cell關(guān)鍵一
@interface ViewController ()
//1. 連線storyboard 獲得 ?UICollectionView 對象
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//2.設(shè)置數(shù)據(jù)源
self.collectionView.dataSource = self;
//3.將collectionView添加到View ?
[self.view addSubview:collectionView];
}
#pragma mark -- . 數(shù)據(jù)源方法的實現(xiàn)
//返回有多少組
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionV iew *)collectionView{
//這里返回一組,如果是返回的多組,要用點語法,加屬性,來計算
return 1;
}
//返回每組有多少 cell
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
//這里返回的是有20個cell,如果是其余的,要根據(jù)具體情況,具體計算
return self.xxx.count;
}
//返回 每個 cell顯示的是什么內(nèi)容
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
//1.注冊ID
static NSString *ID = @"cell";
//2.獲取可重用的cell 如果沒有就自己創(chuàng)建 一個返回 ?:
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
//3.設(shè)置cell 背景
cell.backgroundColor = [UIColor redColor];
//返回cell
return cell;
}