//首先自定义一个 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 < [attributes count]; ++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只显示一行,原因是下面所有cell的x值都被加到第一行最后一个元素的后面了
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;
}