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

UICollectionViewCompositionalLayout.list能否调整项、组、分区间距?

问题解答

使用UICollectionViewCompositionalLayout.list时完全可以调整单元格间距、分区边距,且调整后不会损失TableView级别的渲染性能,也不会影响滑动操作等原生列表特性,具体调整方式分两类:

全局默认间距调整(最简单,性能最优)

直接修改UICollectionLayoutListConfiguration的自带属性即可,所有配置都是列表布局原生支持,无额外性能损耗:

  • 单元格垂直间距:iOS 15及以上系统可直接设置interItemSpacing属性,对应之前手动给item设置的contentInsets.bottom效果,比如要留5pt间距直接写config.interItemSpacing = .fixed(5)
  • 列表整体边距:设置contentInsets属性即可控制所有分区的上下左右边距,对应之前给section设置的leading/trailing边距,比如左右各留5pt可写config.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 5, bottom: 0, trailing: 5)
  • 分区头尾间距:grouped样式下可直接通过headerTopPadding、footerBottomPadding属性调整分区头、分区尾的留白大小

对应基础实现代码:

func setupLayout() -> UICollectionViewCompositionalLayout {
  var config = UICollectionLayoutListConfiguration(appearance: .grouped)
  // 配置滑动操作
  config.trailingSwipeActionsConfigurationProvider = { indexPath in
       return UISwipeActionsConfiguration(actions: [self.makeRemoveAccessContextualAction(forRowAt: indexPath)])
  }
  // 配置全局间距
  config.interItemSpacing = .fixed(5)
  config.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 5, bottom: 0, trailing: 5)
        
  let layout = UICollectionViewCompositionalLayout.list(using: config)
  return layout
}

分区间距/样式差异化调整

如果不同分区需要不同的边距、间距配置,不需要放弃list布局的性能优化,只要给layout设置sectionProvider,在系统生成的默认list section基础上修改对应属性即可,完全保留滑动操作、预加载、高效复用的原生特性。
示例代码:

func setupLayout() -> UICollectionViewCompositionalLayout {
  var config = UICollectionLayoutListConfiguration(appearance: .grouped)
  config.trailingSwipeActionsConfigurationProvider = { indexPath in
       return UISwipeActionsConfiguration(actions: [self.makeRemoveAccessContextualAction(forRowAt: indexPath)])
  }
  // 全局默认配置
  config.interItemSpacing = .fixed(5)
  config.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 5, bottom: 0, trailing: 5)
        
  let layout = UICollectionViewCompositionalLayout.list(using: config)
  // 差异化调整分区配置
  layout.sectionProvider = { sectionIndex, environment in
    guard let section = NSCollectionLayoutSection.list(using: config, layoutEnvironment: environment) else { return nil }
    // 例:给第0个分区设置更大的左右边距、更大的单元格间距
    if sectionIndex == 0 {
      section.contentInsets.leading = 15
      section.contentInsets.trailing = 15
      section.interGroupSpacing = 10
    }
    return section
  }

  return layout
}

注意事项

  • 不要在list布局中手动重新创建NSCollectionLayoutItem、NSCollectionLayoutGroup,直接修改系统生成的list section属性即可,否则会丢失list布局的底层性能优化
  • 单元格内部的内容边距直接在自定义cell的contentView中通过约束调整即可,和UITableViewCell的调整逻辑完全一致,不需要修改布局配置
  • 上述调整方式的底层渲染、复用逻辑和原生UITableView完全一致,性能和纯TableView实现没有差异,完全满足使用要求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 11:42:16