🍓想实现以下的布局,用一个collectionView做到,需要我们自定义UICollectionViewFlowLayout来实现布局,
🍓首先创建一个类继承于```UICollectionViewFlowLayout`` `,详细的代码如下
#define KWIDTH [UIScreen mainScreen].bounds.size.width
#define KHEIGHT [UIScreen mainScreen].bounds.size.height
@interface CustomFlowLayout (){
CGFloat _space;
CGFloat _bigsizeH;
CGFloat _smallSizeH;
CGFloat _sizeW;
CGFloat _cellSpace;
}
@end
@implementation CustomFlowLayout
-(CGSize)collectionViewContentSize{
//这个方法执行两次,分别在生成空白的attributes对象的前后
_space = 5.0; //这是方块之间的间距
_bigsizeH = 200.0; //这里是大方块的高度
_smallSizeH = (_bigsizeH -_space)/2; //小方块的高度
_sizeW = (KWIDTH -_space*2)/2; //方块的宽度
_cellSpace = 2*(_space+_bigsizeH);
NSInteger num = [[self collectionView]numberOfItemsInSection:0];
CGFloat height = ceil(num/3.0)*(_bigsizeH+_space*2+1);
return CGSizeMake(KWIDTH, height);
}//返回contentsize的总大小
-(BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds{
return YES;
}
- (UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)path{
UICollectionViewLayoutAttributes* attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:path];
//生成空白的attributes对象,只记录了类型是cell以及对应的位置是indexPath
//这里我是以6个方块为一组,对它们的坐标进行设置的
CGRect rect = CGRectZero;
NSInteger index = path.item;
if (index%6 == 0) {
int idx = (int)index/6;
rect = CGRectMake(_space, idx*_cellSpace, _sizeW, _bigsizeH);
}else if ((index-1)%6 == 0){
int idx = (int)(index-1)/6;
rect = CGRectMake(_space*2+_sizeW, idx*_cellSpace, _sizeW, _smallSizeH);
}else if ((index-2)%6==0){
int idx = (int)(index-2)/6;
rect = CGRectMake(_space*2+_sizeW, idx*_cellSpace+(_smallSizeH+_space), _sizeW, _smallSizeH);
}else if ((index -3)%6 == 0){
int idx = (int)(index-3)/6;
rect = CGRectMake(_space,idx*_cellSpace+_space+_bigsizeH ,_sizeW, _smallSizeH);
}else if ((index-4)%6 ==0){
int idx = (int)(index-4)/6;
rect = CGRectMake(_space, idx*_cellSpace+2*_space+_bigsizeH+_smallSizeH, _sizeW, _smallSizeH);
}else if ((index-5)%6==0){
int idx = (int)(index-5)/6;
rect = CGRectMake(_space*2+_sizeW, idx*_cellSpace+_bigsizeH+_space, _sizeW, _bigsizeH);
}
attributes.frame = rect;
return attributes;
}
-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect{
NSArray *array = [super layoutAttributesForElementsInRect:rect];
NSMutableArray* attributes = [NSMutableArray array];
for (NSInteger i=0 ; i < [array count]; i++) {
NSIndexPath* indexPath = [NSIndexPath indexPathForItem:i inSection:0];
[attributes addObject:[self layoutAttributesForItemAtIndexPath:indexPath]];
}
return attributes;
}
❤️如果需要改变布局那么就可以改变attributes对象的坐标以达到自己想要的布局效果.
以上😁