在开始前我们在这先附一段最简单的代码
- (void)viewDidLoad { [super viewDidLoad]; UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init]; UICollectionView *colView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout]; colView.backgroundColor = [UIColor grayColor]; [colView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"myCell"]; colView.delegate = self; colView.dataSource = self; [self.view addSubview:colView]; } - (NSArray *)loadData { NSArray *arr = [NSArray arrayWithObjects:@"cell", @"cell2", @"cell3", @"cell4", @"cell5", @"cell6", @"cell7",nil]; return arr; } #pragma mark - UICollectionViewDataSource - (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section { return [[self loadData] count]; } - (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView { return 1; } - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellID = @"myCell"; UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath]; cell.backgroundColor = [UIColor redColor]; return cell; }