??想實(shí)現(xiàn)以下的布局,用一個(gè)collectionView做到,需要我們自定義UICollectionViewFlowLayout來實(shí)現(xiàn)布局,
myCov.png
??首先創(chuàng)建一個(gè)類繼承于```UICollectionViewFlowLayout`` `,詳細(xì)的代碼如下
#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{
//這個(gè)方法執(zhí)行兩次,分別在生成空白的attributes對(duì)象的前后
_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對(duì)象,只記錄了類型是cell以及對(duì)應(yīng)的位置是indexPath
//這里我是以6個(gè)方塊為一組,對(duì)它們的坐標(biāo)進(jìn)行設(shè)置的
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對(duì)象的坐標(biāo)以達(dá)到自己想要的布局效果.
以上??