Subclass UICollectionViewFlowLayout,自定义流布局

需求:为实现第一行显示一个,第二行以后显示两个

方案1:用系统自带的流布局,实现的效果是,若第二行只有一个,则系统默认会居中显示,不是左对齐(如下图),不符合项目要求。

方案2:自定义系统的UICollectionViewFLowLayout,主要代码如下, 只要继承super的layoutAttributes,修改section=0,row=1的Item的X 为0即可

(之前走了很多弯路,)

subclass of UICollectionViewFlowLayout

- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds

{

    return YES;

}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect

{

  NSArray<UICollectionViewLayoutAttributes*>* original = [super layoutAttributesForElementsInRect:rect];

      for (int i=original.count-1; i>=0; i--) {        

        NSIndexPath* indexPath = original[i].indexPath;

        if (nil == original[i].representedElementKind && indexPath.section==0 &&indexPath.row==1) {

            CGRect  frame = original[i].frame;

            frame.origin.x = 0;

            original[i].frame = frame;

        }

  }

    return original;

}

原文地址:https://www.cnblogs.com/Apple2U/p/5434622.html