You need to enable JavaScript to run this app. 如何自定义UICollectionView实现水平左对齐且限制最多显示3行
优惠活动
大模型
产品
解决方案
定价
更多

如何自定义UICollectionView实现水平左对齐且限制最多显示3行

UICollectionView左对齐+最多3行布局实现方案

实现效果参考:
效果示例图

需求明确

  • 单元格水平方向左对齐,行内间距固定,不满一行时靠左排列
  • 内容最多展示3行,超出3行的item不显示

实现方案

方案1:使用UICollectionViewCompositionalLayout(iOS 13+ 推荐)

系统原生布局方案,代码量小易维护:

// 定义单个item尺寸,可根据业务调整为estimated适配动态宽度
let itemSize = NSCollectionLayoutSize(widthDimension: .absolute(80), heightDimension: .absolute(30))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
item.contentInsets = NSDirectionalEdgeInsets(top: 4, leading: 4, bottom: 4, trailing: 4)

// 定义行Group,水平排列,宽度撑满容器
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .absolute(38))
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [item])
// 行内item间距固定,实现左对齐
group.interItemSpacing = .fixed(4)
group.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 8, bottom: 0, trailing: 8)

let section = NSCollectionLayoutSection(group: group)
section.interGroupSpacing = 6 // 行间距
section.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 0, bottom: 8, trailing: 0)

// 数据源层面截断:提前计算3行最多可容纳的item数量,超出后直接截断数据源数组,避免多余渲染
let maxItemPerRow: Int = 5 // 根据item宽度和容器宽度自行计算
let maxShowCount = maxItemPerRow * 3
let showDataList = originalDataList.prefix(maxShowCount)

方案2:自定义UICollectionViewFlowLayout(兼容iOS 13以下版本)

重写系统FlowLayout的布局逻辑,同时实现左对齐和最大行数限制:

class LeftAlignLimitFlowLayout: UICollectionViewFlowLayout {
    /// 最大展示行数,外部可修改
    var maxRowCount: Int = 3
    
    override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
        guard let originAttrs = super.layoutAttributesForElements(in: rect) else { return nil }
        var resultAttrs = [UICollectionViewLayoutAttributes]()
        var currentRowY: CGFloat = -1
        var currentRowStartX: CGFloat = sectionInset.left
        var currentRowIndex: Int = 0
        
        for attrs in originAttrs {
            // 超出最大行数直接丢弃布局
            guard currentRowIndex < maxRowCount else { continue }
            
            // 检测新行
            if attrs.frame.minY != currentRowY {
                currentRowY = attrs.frame.minY
                currentRowStartX = sectionInset.left
                currentRowIndex += 1
                guard currentRowIndex <= maxRowCount else { continue }
            }
            
            // 调整x坐标实现左对齐
            attrs.frame.origin.x = currentRowStartX
            currentRowStartX += attrs.frame.width + minimumInteritemSpacing
            resultAttrs.append(attrs)
        }
        return resultAttrs
    }
    
    // 重写内容尺寸,限制高度最多为3行高度
    override var collectionViewContentSize: CGSize {
        let originSize = super.collectionViewContentSize
        let maxHeight = sectionInset.top + sectionInset.bottom + (itemSize.height + minimumLineSpacing) * CGFloat(maxRowCount) - minimumLineSpacing
        return CGSize(width: originSize.width, height: min(originSize.height, maxHeight))
    }
}

使用方式:

  • 初始化布局后赋值给UICollectionView.collectionViewLayout即可,可自行调整minimumLineSpacing、minimumInteritemSpacing、sectionInset等属性适配业务样式。
  • 动态宽度的item需要实现UICollectionViewDelegateFlowLayout的collectionView(_:layout:sizeForItemAt:)方法返回正确的item尺寸。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 19:15:07