居中对齐
图片.png
@implementation WYTCollectionViewCenterFlowLayout
- (NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *attrsArry = [super layoutAttributesForElementsInRect:rect];
// 最后一行有几个
NSInteger last = attrsArry.count % kLineNum;
if (last == 0) {
return attrsArry;
}
CGFloat itemW = self.itemSize.width;
CGFloat spacing = self.minimumInteritemSpacing;
CGFloat totalW = spacing*(last-1) + itemW*last;
CGFloat startX = (kCollectionViewW - totalW) * 0.5;
// 最后一行起始位置
NSInteger startIndex = attrsArry.count - last;
for (NSInteger i=startIndex; i<attrsArry.count; i++) {
CGFloat x = startX + (attrsArry.count-i-1) * (itemW+spacing);
UICollectionViewLayoutAttributes *curAttr = attrsArry[i];
CGRect frame = curAttr.frame;
frame.origin.x = x;
curAttr.frame = frame;
}
return attrsArry;
}
@end
左对齐
图片.png
@implementation WYTCollectionViewLeftFlowLayout
-(NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
NSArray *attrsArry = [super layoutAttributesForElementsInRect:rect];
for (int i=0; i<attrsArry.count; i++) {
if (i+1 < attrsArry.count) {
UICollectionViewLayoutAttributes *curAttr = attrsArry[i];
UICollectionViewLayoutAttributes *nextAttr = attrsArry[i+1];
//如果下一个在同一行则调整,不在同一行则跳过
if (CGRectGetMinY(curAttr.frame) == CGRectGetMinY(nextAttr.frame)) {
if (CGRectGetMinX(nextAttr.frame) - CGRectGetMaxX(curAttr.frame) > self.minimumInteritemSpacing){
CGRect frame = nextAttr.frame;
frame.origin.x = CGRectGetMaxX(curAttr.frame) + self.minimumInteritemSpacing;
nextAttr.frame = frame;
}
}
}
}
return attrsArry;
}
@end
网友评论