控制器繼承UICollectionViewController 它自動遵守數據源 和 代理了。
1.實現數據源方法
pragma mark - collectionView數據源方法
/**
- 有多少組
*/
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
return 1;
}
/**
- 第section有多少個格子
*/
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return self.products.count;
}
/**
- 返回怎樣cell
*/
-
(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
// 0.聲明重用標示
static NSString *ID = @"Product";
// 1.創建cell
CZProductCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
// cell.backgroundColor = [UIColor orangeColor];// 2.獲得indexPath.item對應product模型
CZProduct *product = self.products[indexPath.item];
cell.product = product;return cell;
}
2。注冊cell (viewDidLoad 方法實現)
(這個cell 是XIB) XIB 里面要設置 彩票那
// 注冊cell(如果緩存池沒有找到對應cell,則會創建該方法注冊的cell)
UINib *nib = [UINib nibWithNibName:@"CZProductCell" bundle:nil];
[self.collectionView registerNib:nib forCellWithReuseIdentifier:@"Product"];
3.布局
- (instancetype)init {
// UICollectionViewLayout *layout = [[UICollectionViewLayout alloc] init];要子類才行 下面這個
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
// 設置item尺寸
layout.itemSize = CGSizeMake(80, 80);
// 設置item之間的間隔
layout.minimumInteritemSpacing = 0;
// 設置行之間間隔
layout.minimumLineSpacing = 20;
// 設置組的內邊距
layout.sectionInset = UIEdgeInsetsMake(20, 0, 0, 0);
if (self = [super initWithCollectionViewLayout:layout]) {
}
return self;
}
另外這種自定義CELL是沒有XIB的
// 注冊cell,默認就會創建這個類型的cell
[self.collectionView registerClass:[CZNewFeatureCell class] forCellWithReuseIdentifier:ID];
// 分頁(這個是新特性那里)
self.collectionView.pagingEnabled = YES;
self.collectionView.bounces = NO;
self.collectionView.showsHorizontalScrollIndicator = NO;
//也是重寫init
-
(instancetype)init
{
UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];// 設置cell的尺寸
layout.itemSize = [UIScreen mainScreen].bounds.size;
// 清空行距
layout.minimumLineSpacing = 0;// 設置滾動的方向
layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;return [super initWithCollectionViewLayout:layout];
}
//UICollectionView被選中時調用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell * cell = (UICollectionViewCell *)[collectionView cellForItemAtIndexPath:indexPath];
cell.backgroundColor = [UIColor whiteColor];
}
//返回這個UICollectionView是否可以被選擇
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}