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

如何在使用UIListContentConfiguration时减小单元格高度(垂直边距)

如何在使用UIListContentConfiguration时减小单元格高度(垂直边距)

我完全懂你的痛点——想在特定页面尽可能多塞内容,结果调了directionalLayoutMargins只搞定了水平边距,垂直高度纹丝不动,这确实挺闹心的!

问题出在你找错了调整对象:directionalLayoutMargins控制的是单元格和集合视图之间的外部边距,而内容区域的垂直留白,得靠UIListContentConfiguration的contentInsets来调整。另外还要确保动态文本的适配逻辑不失效,不然硬改高度会在大字体模式下翻车。

下面给你一套既不硬编码高度、又能完美适配动态文本的解决方案:

1. 调整内容区域的垂直内边距

直接修改contentInsets的top和bottom值,缩小垂直方向的留白。默认的valueCell配置垂直内边距偏大,你可以根据需求设为更小的值(比如8pt),同时保留需要的水平边距:

let cellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Item> { cell, indexPath, item in
    var config = UIListContentConfiguration.valueCell()
    config.text = "Title"
    config.secondaryText = "Value"
    
    // 核心:缩小内容区域的垂直内边距
    config.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 16, bottom: 8, trailing: 16)
    
    // 保留你的水平边距设置(如果需要完全移除水平边距的话)
    config.axesPreservingSuperviewLayoutMargins = []
    config.directionalLayoutMargins = .zero
    
    cell.contentConfiguration = config
}

2. 确保动态文本适配不失效

为了让单元格在用户调整系统文本大小时自动拉伸适配,要给文本属性开启动态适配:

// 给标题设置动态字体
let titleFont = UIFont.preferredFont(forTextStyle: .body)
config.textProperties.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: titleFont)
config.textProperties.adjustsFontForContentSizeCategory = true

// 给副标题设置动态字体
let secondaryFont = UIFont.preferredFont(forTextStyle: .subheadline)
config.secondaryTextProperties.font = UIFontMetrics(forTextStyle: .subheadline).scaledFont(for: secondaryFont)
config.secondaryTextProperties.adjustsFontForContentSizeCategory = true

3. 保持集合视图布局的自动计算

你的布局代码不需要硬改item高度,只要确保UICollectionLayoutListConfiguration不强制固定尺寸,让系统根据内容自动计算即可:

let layout = UICollectionViewCompositionalLayout { sectionIndex, environment in
    let config = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
    // 不需要设置fixedSize,让系统自动适配内容高度
    return NSCollectionLayoutSection.list(using: config, layoutEnvironment: environment)
}

这样调整后,默认字体下单元格高度会回到接近44pt的水平,同时在动态文本模式下会自动拉伸适配内容,完全符合你的需求。

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 07:34:51