MOLeftAlignedFlowLayout.m 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. //
  2. // MOLeftAlignedFlowLayout.m
  3. // MiMoLive
  4. //
  5. // Created by MiMo on 2025/7/8.
  6. //
  7. #import "MOLeftAlignedFlowLayout.h"
  8. @implementation MOLeftAlignedFlowLayout
  9. - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
  10. NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
  11. NSMutableArray *updatedAttributes = [NSMutableArray array];
  12. // 当前行的 left 起点
  13. CGFloat leftMargin = self.sectionInset.left;
  14. CGFloat maxY = -1.0;
  15. for (UICollectionViewLayoutAttributes *attr in attributes) {
  16. // 只处理 cell,跳过 header/footer
  17. if (attr.representedElementCategory == UICollectionElementCategoryCell) {
  18. // 如果是新的一行
  19. if (attr.frame.origin.y >= maxY) {
  20. leftMargin = self.sectionInset.left;
  21. }
  22. CGRect frame = attr.frame;
  23. frame.origin.x = leftMargin;
  24. attr.frame = frame;
  25. leftMargin += frame.size.width + self.minimumInteritemSpacing;
  26. maxY = MAX(CGRectGetMaxY(frame), maxY);
  27. }
  28. [updatedAttributes addObject:attr];
  29. }
  30. return updatedAttributes;
  31. }
  32. @end