0.遵守代理
self.collectionView.delegate = self;self.collectionView.dataSource = self;
1.注册 cell 类
//注册 collectionViewCell [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseID];
2.创建 collectionView
- (void)setupCollectionView{ UICollectionViewFlowLayout *layout = [self layout]; UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 104, SCREENW, SCREENH - 104) collectionViewLayout:layout]; self.collectionView = collectionView;// collectionView.scrollEnabled = NO; collectionView.pagingEnabled = YES;// collectionView.showsHorizontalScrollIndicator = NO; collectionView.backgroundColor = [UIColor lightGrayColor]; collectionView.bounces = NO; [self.view addSubview:collectionView];}
2.1注意:代码创建itemCell 必须指定 layout
- (UICollectionViewFlowLayout *)layout{ UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; layout.minimumInteritemSpacing = 0; layout.minimumLineSpacing = 0; layout.itemSize = CGSizeMake(100, 200); layout.scrollDirection = UICollectionViewScrollDirectionHorizontal; return layout;}
3.实现代理方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { return 1;}- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return 4;}- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseID forIndexPath:indexPath]; NSLog(@"%@",NSStringFromCGRect(cell.frame)); cell.backgroundColor = [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0) green:((float)arc4random_uniform(256) / 255.0) blue:((float)arc4random_uniform(256) / 255.0) alpha:1.0]; return cell;}