// 创建collectView
UICollectionViewFlowLayout *flowLaout = [[UICollectionViewFlowLayout alloc]init];
// 设置item的大小
flowLaout.itemSize = CGSizeMake(180, 240);
// 设置section之间的间距
flowLaout.sectionInset = UIEdgeInsetsMake(0, 100, 100, 100);
// 设置头分区
flowLaout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 30);
// 设置脚分区
flowLaout.footerReferenceSize = CGSizeMake(self.view.frame.size.width, 100);
// item之间的间距
flowLaout.minimumInteritemSpacing = 10;
// item 行之间的间距
flowLaout.minimumLineSpacing = 30;
// 改变滑动方向
// flowLaout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
// 创建collectionView(并用布局类对象初始化集合视图)
self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:flowLaout];
self.collectionView.backgroundColor = [UIColor orangeColor];
self.collectionView.delegate = self;
self.collectionView.dataSource = self;
// 给collectionView注册cell
[self.collectionView registerClass:[RootCollectionViewCell class] forCellWithReuseIdentifier:@"cellId"];
// 给collectionView注册头分区的id
[self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerId"];
// 给collectionView注册脚分区的id
[self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footerId"];
[self.view addSubview:self.collectionView];
pragma mark - 返回头分区和脚分区
(UICollectionReusableView )collectionView:(UICollectionView )collectionView viewForSupplementaryElementOfKind:(NSString )kind atIndexPath:(NSIndexPath )indexPath
{
if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@”headerId” forIndexPath:indexPath];
view.backgroundColor = [UIColor yellowColor];return view;
} else {
UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@”footerId” forIndexPath:indexPath];
view.backgroundColor = [UIColor brownColor];return view;
}
}(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return self.urlsArray.count;
}(UICollectionViewCell )collectionView:(UICollectionView )collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
// RootCollectionViewCell 已经注册给collectionView了所以直接重用就行 , 如果没有.collectionView会自己来的创建,不用我们管创建过程
RootCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@”cellId” forIndexPath:indexPath];cell.label.text = [NSString stringWithFormat:@”贝爷的第%ld个小妾” , indexPath.row + 1];
NSString *urlString = self.urlsArray[indexPath.row];
cell.imageView.imageURL = [NSURL URLWithString:urlString];
// cell.backgroundColor = [UIColor cyanColor];
return cell;
}