iOS:用UICompositionalLayout构建标签列表并移除组内空白
解决UICompositionalLayout话题标签流式布局问题
要实现标签跨两行连续排列、无多余空白的效果,你需要调整布局的group类型和尺寸设置,具体修改如下:
修改后的代码
let itemSize = NSCollectionLayoutSize(widthDimension: .estimated(120), heightDimension: .absolute(44)) let layoutItem = NSCollectionLayoutItem(layoutSize: itemSize) // 缩小内边距,让标签排列更紧凑 layoutItem.contentInsets = NSDirectionalEdgeInsets(top: 4, leading: 4, bottom: 4, trailing: 4) // 创建横向流式布局group,宽度自适应内容,高度预估两行标签的总高度 let groupSize = NSCollectionLayoutSize(widthDimension: .estimated(CGFloat.greatestFiniteMagnitude), heightDimension: .estimated(88)) let layoutGroup = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitems: [layoutItem]) // 取消item间额外间距(内边距已控制标签间距) layoutGroup.interItemSpacing = .fixed(0) let layoutSection = NSCollectionLayoutSection(group: layoutGroup) layoutSection.orthogonalScrollingBehavior = .continuous // 给section添加整体内边距,优化视觉效果 layoutSection.contentInsets = NSDirectionalEdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 8) return layoutSection
关键修改点
- 替换布局group类型:把原来的垂直分组(
vertical)改成水平分组(horizontal),让标签可以自动换行,实现流式排列。 - 调整group尺寸约束:去掉固定宽度的限制,改用
estimated(CGFloat.greatestFiniteMagnitude)让group自适应标签内容宽度;高度设为预估的两行总高度,确保能容纳多行标签。 - 优化内边距设置:缩小item的内边距,避免不必要的空白,同时给section添加整体内边距提升视觉体验。
内容的提问来源于stack exchange,提问作者Sarthak Mishra
相关产品推荐
相关产品推荐

