如何自定义UICollectionView Cell尺寸,实现交替行列布局?
解决方案
直接沿用你原有的间距与高度计算逻辑,通过判断item索引在循环周期内的位置,返回对应尺寸即可实现需求布局,代码如下:
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { let spacing: CGFloat = 12 // 基础小Cell宽度,和你原计算逻辑一致 let baseWidth = (self.view.frame.size.width - spacing * 3) / 3 let baseHeight = baseWidth * 1.5 // 布局循环周期:3小 → 1大1小 → 3小 → 1小1大,共10个item let cycleTotalCount = 3 + 2 + 3 + 2 let cycleIndex = indexPath.item % cycleTotalCount switch cycleIndex { case 0...2, 5...7: // 第一、第三行等循环位置的小Cell return CGSize(width: baseWidth, height: baseHeight) case 3: // 第二行第一个大Cell,宽度占满剩余空间(减去小Cell和间距) let largeWidth = self.view.frame.size.width - baseWidth - spacing return CGSize(width: largeWidth, height: baseHeight) case 4, 8: // 第二行第二个、第四行第一个的小Cell return CGSize(width: baseWidth, height: baseHeight) case 9: // 第四行第二个大Cell,宽度占满剩余空间 let largeWidth = self.view.frame.size.width - baseWidth - spacing return CGSize(width: largeWidth, height: baseHeight) default: // 默认返回小Cell尺寸 return CGSize(width: baseWidth, height: baseHeight) } }
补充配置
为保证间距与计算匹配,需设置UICollectionViewFlowLayout的相关属性:
if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout { flowLayout.minimumInteritemSpacing = 12 flowLayout.minimumLineSpacing = 12 flowLayout.sectionInset = UIEdgeInsets(top: 0, left: 12, bottom: 0, right: 12) }
逻辑说明
- 基础参数:保留你原有的小Cell宽高计算逻辑,保证第一、第三行等布局和原效果一致。
- 循环周期:以10个item为一个循环单元(3+2+3+2),通过取模运算定位当前item在周期内的位置。
- 尺寸分配:
- 周期内
0-2、5-7位置:返回基础小Cell尺寸,对应第一、第三行等布局; - 周期内
3、9位置:返回大Cell尺寸,宽度为屏幕宽度减去一个小Cell宽度和间距,确保和同行的小Cell加间距后占满整行; - 周期内
4、8位置:返回小Cell尺寸,对应第二行第二个、第四行第一个Cell。
- 周期内
内容的提问来源于stack exchange,提问作者Sanjay Mishra
相关产品推荐
相关产品推荐

