依然繼承UICollectionViewFlowLayout?
然后重寫- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect 方法 ,
但是都是section為1 的情況 ?特此補(bǔ)充一下 多組情況下的判斷
- (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray*original = [superlayoutAttributesForElementsInRect:rect];
NSMutableArray*attributes = [[NSMutableArrayalloc]initWithArray:originalcopyItems:YES];
//從第二個(gè)循環(huán)到最后一個(gè),因?yàn)榈谝粋€(gè)不需要修改
for(inti =1; i < [attributescount]; i++) {
//當(dāng)前attributes
UICollectionViewLayoutAttributes*currentLayoutAttributes = attributes[i];
LOG(@"%@",currentLayoutAttributes.frame);
//上一個(gè)attributes
UICollectionViewLayoutAttributes*prevLayoutAttributes = attributes[i -1];
LOG(@"%@",prevLayoutAttributes.frame);
//設(shè)置的Cell間距沼撕,可根據(jù)需要改
NSIntegercellSpacing =10;
//前一個(gè)cell的最右邊
NSIntegerprevCellRight =CGRectGetMaxX(prevLayoutAttributes.frame);
//如果當(dāng)前一個(gè)cell的最右邊加上我們想要的間距加上當(dāng)前cell的寬度依然在contentSize中嗽上,我們改變當(dāng)前cell的原點(diǎn)位置
//不加這個(gè)判斷的后果是泪酱,UICollectionView只顯示一行倡勇,原因是下面所有cell的x值都被加到第一行最后一個(gè)元素的后面了
if(prevCellRight + cellSpacing + currentLayoutAttributes.frame.size.width
//判斷是否是一個(gè)組瞄桨,不然你會(huì)發(fā)現(xiàn)prevCellRight拿到的是上一組最后一個(gè)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;
}