最近在项目中遇到设置CollectionView左对齐的问题,就想到了设置CollectionView最大间距即可解决左对齐的问题,话不多说,直接上代码
-(NSArray <UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect{
NSArray *array = [super layoutAttributesForElementsInRect:rect];
int index =0;
UICollectionViewLayoutAttributes *last;
for(UICollectionViewLayoutAttributes *current in array) {
if(index >0) {
float maxSpacing = 10;
float maxX = CGRectGetMaxX(last.frame);
if(maxX + maxSpacing + current.frame.size.width < self.collectionViewContentSize.width) {
CGRect frame = current.frame;
frame.origin.x= maxX + maxSpacing;
current.frame= frame;
}
}
index ++;
last = current;
}
return array;
}
只需新建一个UICollectionViewFlowLayout,重写他的 layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? 方法即可
作者:BeSt2wazi
链接://www.greatytc.com/p/d3d3162f448c
來源:简书