首先知識點
1 獲取一個view的最右邊的x值
CGRectGetMaxX(prevLayoutAttributes.frame);
2 獲取一個view的最下面y值
CGRectGetMaxY(prevLayoutAttributes.frame);
3 uicollectionViewFlowLayout有個layoutAttributesForElementsInRect方法,這個方法返回所有的cell的布局參數(shù)的數(shù)組
4 解決方法
重寫layoutAttributesForElementsInRect方法
-
(NSArray *) layoutAttributesForElementsInRect:(CGRect)rect {
// 獲取系統(tǒng)幫我們計算好的Attributes
NSArray *answer = [super layoutAttributesForElementsInRect:rect];// 遍歷結(jié)果
for(int i = 1; i < [answer count]; ++i) {// 獲取cell的Attribute,根據(jù)上一個cell獲取最大的x,定義為origin UICollectionViewLayoutAttributes *currentLayoutAttributes = answer[i]; UICollectionViewLayoutAttributes *prevLayoutAttributes = answer[i - 1]; //此處根據(jù)個人需求,我的需求里面有head cell兩類,我只需要調(diào)整cell,所以head直接過濾 if([currentLayoutAttributes.representedElementKind isEqualToString:UICollectionElementKindSectionHeader]){ continue; } NSInteger preX = CGRectGetMaxX(prevLayoutAttributes.frame); NSInteger preY = CGRectGetMaxY(prevLayoutAttributes.frame); NSInteger curY = CGRectGetMaxY(currentLayoutAttributes.frame); // 設(shè)置cell最大間距 NSInteger maximumSpacing = 0; // 如果當(dāng)前cell和precell在同一行 if(preY == curY){ //滿足則給當(dāng)前cell的frame屬性賦值 //不滿足的cell會根據(jù)系統(tǒng)布局換行 CGRect frame = currentLayoutAttributes.frame; frame.origin.x = preX + maximumSpacing; currentLayoutAttributes.frame = frame; }}
return answer;
}