// // MORecommendFlowLayout.m // MiMoLive // // Created by SuperC on 2025/3/3. // #import "MORecommendFlowLayout.h" @implementation MORecommendFlowLayout - (NSArray *)layoutAttributesForElementsInRect:(CGRect)rect { NSMutableArray *attributesArray = [[super layoutAttributesForElementsInRect:rect] mutableCopy]; // 获取 CollectionView 的宽度 CGFloat collectionViewWidth = self.collectionView.bounds.size.width; // 假设 item 的大小(3 列时计算) CGFloat itemWidth = (collectionViewWidth - 40) / 3; CGFloat itemHeight = 120.0; // 间距 CGFloat spacing = 10; CGFloat lineSpacing = 15; NSInteger row = 0; // 记录当前的行号 NSInteger itemIndexInRow = 0; // 记录当前行的 item 位置 NSInteger totalItems = [self.collectionView numberOfItemsInSection:0]; for (UICollectionViewLayoutAttributes *attributes in attributesArray) { NSInteger index = attributes.indexPath.item; // 确定当前行是 3 个还是 2 个 item BOOL isThreeItemsRow = (row % 2 == 0); NSInteger itemsInRow = isThreeItemsRow ? 3 : 2; // 计算 X 坐标,使其左右对称 CGFloat x; if (itemsInRow == 3) { x = spacing + itemIndexInRow * (itemWidth + spacing); } else { x = (collectionViewWidth - 2 * itemWidth - spacing) / 2 + itemIndexInRow * (itemWidth + spacing); } // 计算 Y 坐标 CGFloat y = row * (itemHeight + lineSpacing); attributes.frame = CGRectMake(x, y, itemWidth, itemHeight); // 更新当前行内的 index itemIndexInRow++; // 如果当前行已满,则换到下一行 if (itemIndexInRow >= itemsInRow) { row++; itemIndexInRow = 0; } } return attributesArray; } @end