实现的效果图如下:
‘
这个collectview有四个section,分别有4,1,4,4个item。
- (void)viewDidLoad
{
[super viewDidLoad];
self.collectView.delegate = self;
self.collectView.dataSource = self;
self.identifys = @[@"cell1",@"cell2",@"cell3",@"cell4"];
NSArray *classes = @[[oneCell class],[twoCell class],[threeCell class],[FourCell class]];
for (int i = 0; i < 4; i++) {
[self registerForCellFromClass:classes[i] indentify:self.identifys[i]];
}
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
#warning 设定全局行间距
flowLayout.minimumLineSpacing = 20;
flowLayout.headerReferenceSize = CGSizeMake(0, 20);
flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
#warning 下面一句是必须要写的
self.collectView.collectionViewLayout = flowLayout;
}
- (void)registerForCellFromClass:(Class)class indentify:(NSString *)indentify
{
[self.collectView registerClass:class forCellWithReuseIdentifier:indentify];
}
- (UICollectionViewCell *)returnCellFromIndexPath:(NSIndexPath *)indexPath
{
return [self.collectView dequeueReusableCellWithReuseIdentifier:self.identifys[indexPath.section] forIndexPath:indexPath];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell;
switch (indexPath.section) {
case kFirst:{
oneCell *cell1 = (oneCell *)[self returnCellFromIndexPath:indexPath];
cell1.imageView.image = [UIImage imageNamed:@"20111021190309-565119129.jpg"];
cell1.label.text = @"girl";
cell = cell1;
}
break;
case kSecond: {
twoCell *cell2 = (twoCell *)[self returnCellFromIndexPath:indexPath];
cell2.imageView.image = [UIImage imageNamed:@"20111021190309-565119129.jpg"];
cell2.titleLabel.text = @"hello";
cell2.detailLabel.text = @"hi";
cell = cell2;
}
break;
case kThird: {
threeCell *cell3 = (threeCell *)[self returnCellFromIndexPath:indexPath];
cell3.label.text = @"nihao";
cell = cell3;
}
break;
case kFour:{
FourCell *cell4 = (FourCell *)[self returnCellFromIndexPath:indexPath];
cell4.imageView.image = [UIImage imageNamed:@"20111021190309-565119129.jpg"];
cell = cell4;
}
break;
default:
break;
}
cell.backgroundColor = [UIColor whiteColor];
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
CGSize size;
switch (indexPath.section) {
case kFirst:
size = CGSizeMake(140, 45);
break;
case kSecond:
size = CGSizeMake(300, 80);
break;
case kThird:
size = CGSizeMake(140, 40);
break;
case kFour:
size = CGSizeMake(60, 60);
break;
default:
break;
}
return size;
}