例子:一个正方形里面排列不同大小的cell
1.继承UICollectionViewLayout
2.重写-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
//设置所有cell的布局属性
-(NSArray *)layoutAttributesForElementsInRect:(CGRect)rect
{
NSArray *arr = [super layoutAttributesForElementsInRect:rect];
if ([arr count] > 0) {
return arr;
}
NSMutableArray *attributes = [NSMutableArray array];
for (NSInteger i = 0 ; i < [self.collectionView numberOfItemsInSection:0]; i++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:i inSection:0];
[attributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
}
return attributes;
}
3.重写
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
CGFloat width = self.collectionView.width;
NSInteger count = [self.collectionView numberOfItemsInSection:0];
if (count == 1) {
attributes.size = CGSizeMake(width, width);
attributes.center = CGPointMake(width/2, width/2);
}else if (count == 2){
CGFloat x = 0;
CGFloat height = (self.collectionView.width-self.margin)/2;
CGFloat y = indexPath.row * (height+self.margin);
attributes.frame = CGRectMake(x, y, width, height);
}
else if (count == 3) {
width = (self.collectionView.width-self.margin)/2;
CGFloat height = (self.collectionView.width-self.margin)/2;
CGFloat y = 0;
CGFloat x = (indexPath.row-1) * (width + self.margin);
if (indexPath.row == 0) {
x = 0;
y = 0;
width = self.collectionView.width;
}else {
y = height + self.margin;
}
attributes.frame = CGRectMake(x, y, width, height);
}
else if (count == 4) {
width = (self.collectionView.width-self.margin)/2;
CGFloat y = 0;
CGFloat x = 0;
CGFloat height = width;
x = indexPath.row%2 * (width + self.margin);
if (indexPath.row < 2) {
}else {
y = height + self.margin;
}
attributes.frame = CGRectMake(x, y, width, height);
}else if (count == 5) {
CGFloat height = 0;
CGFloat x = 0;
CGFloat y = 0;
if (indexPath.row == 0) {
width = (self.collectionView.width-self.margin)/3*2;
height = self.collectionView.width;
}else {
width = (self.collectionView.width-self.margin)/3;
height = (self.collectionView.width - self.margin *3)/4;
x = (self.collectionView.width-self.margin)/3*2 +self.margin;
y = (indexPath.row -1) * (height + self.margin);
}
attributes.frame = CGRectMake(x, y, width, height);
}else if (count == 6){
width = (self.collectionView.width-self.margin)/2;
CGFloat height = (self.collectionView.width-self.margin*2)/3;
CGFloat y = 0;
CGFloat x = 0;
x = indexPath.row%2 * (width + self.margin);
y = (indexPath.row/2)*(height +self.margin);
attributes.frame = CGRectMake(x, y, width, height);
}
return attributes;
}
572C3B9B-2879-455F-8C7E-732BFDA6056F.png