SquareLayout方形布局

  • 需要實(shí)現(xiàn)的效果圖
效果圖
  • 代碼
#import "SquareLayout.h"

@interface SquareLayout ()
/** attrs的數(shù)組 */
@property(nonatomic,strong)NSMutableArray * attrsArr;
@end
@implementation SquareLayout

-(NSMutableArray *)attrsArr
{
    if(!_attrsArr){
        _attrsArr=[[NSMutableArray alloc] init];
    }
    return _attrsArr;
}

-(void)prepareLayout
{
    [super prepareLayout];
    [self.attrsArr removeAllObjects];
    NSInteger count =[self.collectionView   numberOfItemsInSection:0];
    for (int i=0; i<count; i++) {
        NSIndexPath *  indexPath =[NSIndexPath indexPathForItem:i inSection:0];
        UICollectionViewLayoutAttributes * attrs=[self layoutAttributesForItemAtIndexPath:indexPath];
       [self.attrsArr addObject:attrs];
    }
}

-(NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    return self.attrsArr;
}

#pragma mark ---- 返回CollectionView的內(nèi)容大小
/*!
 * 如果不設(shè)置這個(gè)的話  CollectionView就不能滑動(dòng)
 */
-(CGSize)collectionViewContentSize
{
    int count =(int)[self.collectionView numberOfItemsInSection:0];
    int rows=(count +3 -1)/3;
    CGFloat rowH = self.collectionView.frame.size.width/2;
        if ((count)%6==2|(count)%6==4) {
            return CGSizeMake(0, rows * rowH-rowH/2);
        }else{
            return CGSizeMake(0, rows*rowH);
        }
}



-(UICollectionViewLayoutAttributes *)layoutAttributesForItemAtIndexPath:(NSIndexPath *)indexPath
{
       CGFloat width =self.collectionView.frame.size.width*0.5;
        UICollectionViewLayoutAttributes * attrs=[UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        CGFloat height =width;
        NSInteger i=indexPath.item;
            if (i==0) {
                attrs.frame = CGRectMake(0, 0, width, height);
            }else if (i==1){
                attrs.frame = CGRectMake(width, 0, width, height/2);
            }else if (i==2){
                attrs.frame = CGRectMake(width, height/2, width, height/2);
            }else if (i==3){
                attrs.frame = CGRectMake(0, height, width, height/2);
            }else if (i==4){
                attrs.frame = CGRectMake(0, height+height/2, width, height/2);
            }else if (i==5){
                attrs.frame = CGRectMake(width, height, width, height);
            }else{
               UICollectionViewLayoutAttributes *lastAttrs = self.attrsArr[i-6];
                CGRect frame  = lastAttrs.frame;
                frame.origin.y+=2 * height;
                attrs.frame=frame;
            }
   return attrs;
}

@end

Demo:GitHub地址
上一篇:CircleLayout圓形布局
下一篇 :瀑布流布局

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容