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

iOS:如何在CollectionView CompositionalLayout中实现Section水平排列?

实现UICollectionView CompositionalLayout的Section水平排列

完全可以实现Section水平排列的效果,核心是通过配置组的布局方向和Section的滚动行为来达成,以下是具体实现方案:

核心思路

将整个CollectionView的滚动方向设为垂直,同时让每个Section的组(NSCollectionLayoutGroup)以水平方向排列Item,再开启Section的横向滚动行为,就能实现你参考图中「垂直排列多个Section,每个Section内部Item横向滚动」的效果。

完整代码示例(Swift)

import UIKit

class HorizontalSectionsVC: UIViewController, UICollectionViewDataSource {
    
    private lazy var collectionView: UICollectionView = {
        // 创建CompositionalLayout
        let layout = UICollectionViewCompositionalLayout { _, _ in
            // 1. 定义Item尺寸:占组宽度的1/3,高度与组一致
            let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1/3),
                                                 heightDimension: .fractionalHeight(1))
            let item = NSCollectionLayoutItem(layoutSize: itemSize)
            item.contentInsets = NSDirectionalEdgeInsets(top: 4, leading: 4, bottom: 4, trailing: 4)
            
            // 2. 定义Group尺寸:高度固定200,宽度根据内容自适应
            let groupSize = NSCollectionLayoutSize(widthDimension: .estimated(200),
                                                  heightDimension: .absolute(200))
            // 组方向设为水平,添加Item
            let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
            
            // 3. 创建Section并配置横向滚动
            let section = NSCollectionLayoutSection(group: group)
            section.contentInsets = NSDirectionalEdgeInsets(top: 16, leading: 16, bottom: 16, trailing: 16)
            // 开启Section横向滚动,支持连续滑动
            section.orthogonalScrollingBehavior = .continuous
            
            return section
        }
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        collectionView.backgroundColor = .systemBackground
        return collectionView
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(collectionView)
        collectionView.frame = view.bounds
        collectionView.dataSource = self
    }
    
    // MARK: - UICollectionViewDataSource
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 5 // 模拟5个水平排列的Section
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return 6 // 每个Section包含6个Item
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
        cell.backgroundColor = .random
        return cell
    }
}

// 辅助工具:生成随机颜色
extension UIColor {
    static var random: UIColor {
        UIColor(red: CGFloat.random(in: 0...1),
                green: CGFloat.random(in: 0...1),
                blue: CGFloat.random(in: 0...1),
                alpha: 1)
    }
}

关键配置说明

  • section.orthogonalScrollingBehavior = .continuous:开启Section的横向滚动,当Item数量超出屏幕宽度时,用户可左右滑动查看更多内容,这是实现参考图效果的核心。
  • 组的宽度使用.estimated(200):让Group根据Item数量自动适配宽度,也可根据需求改为.absolute()(固定宽度)或.fractionalWidth(1)(占满屏幕宽度)。
  • 内边距调整:通过item.contentInsets和section.contentInsets控制Item之间、Section与屏幕边缘的间距,匹配设计需求。

拓展调整

如果不需要Section横向滚动,只需去掉orthogonalScrollingBehavior配置,同时将Group的宽度设为.fractionalWidth(1),即可让Section占满屏幕宽度,Item在水平方向均匀排列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 18:12:51