IOS开发 把长度不等的UICollectionView 的cell 居左

来源:互联网 发布:华东师大公共数据 编辑:程序博客网 时间:2024/04/27 21:45

//首先自定义一个 EqualSpaceFlowLayout的类继承于 UICollectionViewFlowLayout

//在.h文件中

@protocol  EqualSpaceFlowLayoutDelegate<UICollectionViewDelegateFlowLayout>


@end


@interface EqualSpaceFlowLayout :UICollectionViewFlowLayout



@property (nonatomic,strong)NSMutableArray *itemAttributes;



@property (nonatomic,weak)id<EqualSpaceFlowLayoutDelegate> delegate;


@end


//在.m文件中 直接粘贴下面的代码就行了

-(NSArray*)layoutAttributesForElementsInRect:(CGRect)rect

{

    NSMutableArray* attributes = [[superlayoutAttributesForElementsInRect:rect]mutableCopy];


    for(int i =1; i < [attributescount]; ++i) {

        

        

        //当前attributes

        UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];

        //上一个attributes

        UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i -1];

    

//        NSLog(@"%ld  %ld", currentLayoutAttributes.indexPath.section, currentLayoutAttributes.indexPath.row);

        

        if (currentLayoutAttributes.indexPath.section == prevLayoutAttributes.indexPath.section && currentLayoutAttributes.frame.origin.x != 0
) {

           //我们想设置的最大间距,可根据需要改

            NSInteger maximumSpacing = 10;

            //前一个cell的最右边

            NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);

           //如果当前一个cell的最右边加上我们想要的间距加上当前cell的宽度依然在contentSize中,我们改变当前cell的原点位置

           //不加这个判断的后果是,UICollectionView只显示一行,原因是下面所有cellx值都被加到第一行最后一个元素的后面了

            if( origin + maximumSpacing + currentLayoutAttributes.frame.size.width <=self.collectionViewContentSize.width-10) {

                

                CGRect frame = currentLayoutAttributes.frame;

                frame.origin.x = origin + maximumSpacing;

                currentLayoutAttributes.frame = frame;

                

            }

            else {

                CGRect frame = currentLayoutAttributes.frame;

                frame.origin.x = maximumSpacing;

                frame.origin.y =CGRectGetMaxY(prevLayoutAttributes.frame) + maximumSpacing;

                currentLayoutAttributes.frame = frame;

            }


        }

    }

    return attributes;

}

0 0
原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 宜家购物卡的钱怎么办 武商购物卡过期怎么办 丹尼斯卡过期了怎么办 联华ok卡过期了怎么办 汉购通过期了怎么办 天猫退货要检测报告怎么办 京东退货后发票怎么办 京东金融被盗刷怎么办 京东e卡丢了怎么办 京东e卡没有密码怎么办 同一个订单微信付款两次怎么办 京东购物卡掉了怎么办 京东购物卡丢了怎么办 京东快递丢了怎么办 京东e卡支付多了怎么办 京东帐号忘了怎么办 京东白条风控怎么办 我有个破袄…没有衣服怎么办办 轩辕传奇手游灵宠融合错了怎么办 各尧学生不能用怎么办? 山东一卡通商务卡丢了怎么办 和信通过期了怎么办 和信通过期怎么办延期 和信通过期余额怎么办 超市储蓄卡丢了怎么办 提现提到注销卡怎么办 美通卡过期2年了怎么办 物美美通卡丢失怎么办 网上购物电话留错了怎么办 微信斗牛一直输怎么办 微信斗牛输了钱怎么办 微信举报诈骗不成功该怎么办 沙河拿服装太贵怎么办 包上的暗扣掉了怎么办 银手镯暗扣松老是掉怎么办 包包纽扣锁坏了怎么办 包的纽扣坏了怎么办 包上的纽扣坏了怎么办 洗衣服不小心用了色渍净怎么办 洗衣服不小心沾了卫生纸怎么办 麻料裤子扎皮肤怎么办