iOS collectionView cell间距问题补充

依然继承UICollectionViewFlowLayout 

然后重写- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect 方法 ,

但是都是section为1 的情况  特此补充一下 多组情况下的判断

- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {

NSArray*original = [superlayoutAttributesForElementsInRect:rect];

NSMutableArray*attributes = [[NSMutableArrayalloc]initWithArray:originalcopyItems:YES];

//从第二个循环到最后一个,因为第一个不需要修改

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

//当前attributes

UICollectionViewLayoutAttributes*currentLayoutAttributes = attributes[i];

LOG(@"%@",currentLayoutAttributes.frame);

//上一个attributes

UICollectionViewLayoutAttributes*prevLayoutAttributes = attributes[i -1];

LOG(@"%@",prevLayoutAttributes.frame);

//设置的Cell间距,可根据需要改

NSIntegercellSpacing =10;

//前一个cell的最右边

NSIntegerprevCellRight =CGRectGetMaxX(prevLayoutAttributes.frame);

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

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

if(prevCellRight + cellSpacing + currentLayoutAttributes.frame.size.width

//判断是否是一个组,不然你会发现prevCellRight拿到的是上一组最后一个cell的frame值

if(currentLayoutAttributes.indexPath.section== prevLayoutAttributes.indexPath.section) {

CGRectframe = currentLayoutAttributes.frame;

frame.origin.x= prevCellRight + cellSpacing;

currentLayoutAttributes.frame= frame;

}else{

CGRectframe = currentLayoutAttributes.frame;

frame.origin.x=0;

currentLayoutAttributes.frame= frame;

}

}else{

CGRectframe = currentLayoutAttributes.frame;

frame.origin.x=0;

currentLayoutAttributes.frame= frame;

}

}

returnattributes;

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容