MORecommendFlowLayout.m 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //
  2. // MORecommendFlowLayout.m
  3. // MiMoLive
  4. //
  5. // Created by SuperC on 2025/3/3.
  6. //
  7. #import "MORecommendFlowLayout.h"
  8. @implementation MORecommendFlowLayout
  9. - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
  10. NSMutableArray *attributesArray = [[super layoutAttributesForElementsInRect:rect] mutableCopy];
  11. // 获取 CollectionView 的宽度
  12. CGFloat collectionViewWidth = self.collectionView.bounds.size.width;
  13. // 假设 item 的大小(3 列时计算)
  14. CGFloat itemWidth = (collectionViewWidth - 40) / 3;
  15. CGFloat itemHeight = 120.0;
  16. // 间距
  17. CGFloat spacing = 10;
  18. CGFloat lineSpacing = 15;
  19. NSInteger row = 0; // 记录当前的行号
  20. NSInteger itemIndexInRow = 0; // 记录当前行的 item 位置
  21. NSInteger totalItems = [self.collectionView numberOfItemsInSection:0];
  22. for (UICollectionViewLayoutAttributes *attributes in attributesArray) {
  23. NSInteger index = attributes.indexPath.item;
  24. // 确定当前行是 3 个还是 2 个 item
  25. BOOL isThreeItemsRow = (row % 2 == 0);
  26. NSInteger itemsInRow = isThreeItemsRow ? 3 : 2;
  27. // 计算 X 坐标,使其左右对称
  28. CGFloat x;
  29. if (itemsInRow == 3) {
  30. x = spacing + itemIndexInRow * (itemWidth + spacing);
  31. } else {
  32. x = (collectionViewWidth - 2 * itemWidth - spacing) / 2 + itemIndexInRow * (itemWidth + spacing);
  33. }
  34. // 计算 Y 坐标
  35. CGFloat y = row * (itemHeight + lineSpacing);
  36. attributes.frame = CGRectMake(x, y, itemWidth, itemHeight);
  37. // 更新当前行内的 index
  38. itemIndexInRow++;
  39. // 如果当前行已满,则换到下一行
  40. if (itemIndexInRow >= itemsInRow) {
  41. row++;
  42. itemIndexInRow = 0;
  43. }
  44. }
  45. return attributesArray;
  46. }
  47. @end