0.遵守代理
self.collectionView.delegate = self;self.collectionView.dataSource = self;
1.注冊(cè) cell 類(lèi)
//注冊(cè) collectionViewCell [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseID];
2.創(chuàng)建 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注意:代碼創(chuàng)建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.實(shí)現(xiàn)代理方法
- (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;}