美文网首页
iOS collectionView cell间距问题补充

iOS collectionView cell间距问题补充

作者: 蜜语酸橙 | 来源:发表于2017-11-14 23:45 被阅读21次

依然继承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;

}

相关文章

网友评论

      本文标题:iOS collectionView cell间距问题补充

      本文链接:https://www.haomeiwen.com/subject/ygmqvxtx.html