1,建立 .h文件
#import <UIKit/UIKit.h>
@interface AKCustomerFlowLayout : UICollectionViewFlowLayout
@end
2,实现文件 .m
#import "AKCustomerFlowLayout.h"
@implementation AKCustomerFlowLayout
- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
NSArray *attributesArray = [super layoutAttributesForElementsInRect:rect];
for (int i = 1;i<[attributesArray count];i++){
UICollectionViewLayoutAttributes *currentFrame = attributesArray[i];
UICollectionViewLayoutAttributes *preFrame = attributesArray[i-1];
CGFloat mimSpace = 1.0;
CGFloat originX = CGRectGetMaxX(preFrame.frame);
CGFloat originY = CGRectGetMaxY(preFrame.frame);
if (originX + mimSpace + currentFrame.frame.size.width <= self.collectionViewContentSize.width){
CGRect frame = currentFrame.frame;
frame.origin.x = originX + mimSpace;
frame.origin.y = preFrame.frame.origin.y;
currentFrame.frame = frame;
}else{
CGRect frame = currentFrame.frame;
frame.origin.y = originY + mimSpace;
currentFrame.frame = frame;
}
}
return attributesArray;
}
@end
3,将自定义的flowlayout添加至collectionView
AKCustomerFlowLayout *layout = [AKCustomerFlowLayout alloc]init];
UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:self.view.bounds CollectionViewLayout:layout];