You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift如何实现横向滚动UICollectionView的两个分组各独占一行

解决方案

问题原因

你当前使用的系统默认UICollectionViewFlowLayout在滚动方向设为横向时,默认会将不同section的cell左右并排排布在同一行,因此会出现红色、蓝色单元格混排的情况。同时你把item的高度设为和collectionView等高的200,也导致布局只能容纳一行内容。

推荐实现方案(iOS13+)

优先使用系统提供的UICollectionViewCompositionalLayout实现,代码简洁易维护,直接替换你viewDidLoad中的布局相关代码即可:

override func viewDidLoad() {
    super.viewDidLoad()
    
    let itemWidth = UIScreen.main.bounds.width / 4.1
    let rowHeight = (collectionView.bounds.height - 5) / 2 // 总高200,减去两行之间的5间距,每行高97.5

    let layout = UICollectionViewCompositionalLayout(sectionProvider: { sectionIndex, _ in
        // 定义单个cell的尺寸
        let item = NSCollectionLayoutItem(
            layoutSize: .init(
                widthDimension: .absolute(itemWidth),
                heightDimension: .absolute(rowHeight)
            )
        )
        
        // 定义section内的排布规则:横向排列cell
        let group = NSCollectionLayoutGroup.horizontal(
            layoutSize: .init(
                widthDimension: .estimated(10000), // 宽度自适应cell总数量
                heightDimension: .absolute(rowHeight)
            ),
            subitems: [item]
        )
        group.interItemSpacing = .fixed(5) // 对应你之前设置的行间距5
        
        let section = NSCollectionLayoutSection(group: group)
        // 两个section之间留5的间距
        section.contentInsets = sectionIndex == 0 ?
            .init(top: 0, leading: 0, bottom: 5, trailing: 0) :
            .init(top: 5, leading: 0, bottom: 0, trailing: 0)
        return section
    })
    
    // 设置全局滚动方向为横向
    let config = UICollectionViewCompositionalLayoutConfiguration()
    config.scrollDirection = .horizontal
    layout.configuration = config
    
    self.collectionView.collectionViewLayout = layout
    collectionView.reloadData()
}

iOS13以下兼容方案

如果需要支持更低系统版本,可自定义UICollectionViewLayout,重写布局属性计算逻辑:

  • 手动调整每个section的cell的y轴偏移:section0所有cell的y值设为0,高度为97.5;section1所有cell的y值设为102.5,高度为97.5
  • 所有cell按顺序计算x轴位置,整个collectionView的contentSize宽度取两个section总宽度的最大值,高度固定为200即可

内容的提问来源于stack exchange,提问作者anySwift

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 17:48:03