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

SwiftUI List设置listRowInsets不生效 无法添加单元格间距怎么办?

问题原因

  • listRowInsets 修饰符的作用对象错误,你需要将它添加到ForEach循环输出的每个行根视图上,而不是行内的子组件上。
  • 你设置的top和bottom参数为0,自然不会产生上下方向的单元格间距,想要行间距需要将这两个值设为正数。
  • InsetGroupedListStyle 默认自带组内连续单元格样式,要实现卡片式分割还需要配合自定义行背景消除默认的单元格连接样式。

正确实现代码

var body: some View {
    List {
        Section(header: Text("Verses")) {
            ForEach(self.viewModel.verses) { verse in
                NavigationLink(destination: VerseDetailView(verse: verse), label: {
                    VStack(alignment: .leading, spacing: 6) {
                        Text(verse.verse).fontWeight(.medium)
                        Text("No \(verse.verse_number)").foregroundColor(.gray)
                    }
                    .padding(10)
                })
                // 配置行边距,上下值控制单元格之间的间距
                .listRowInsets(.init(top: 8, leading: 16, bottom: 8, trailing: 16))
                // 自定义行背景实现卡片圆角效果
                .listRowBackground(
                    RoundedRectangle(cornerRadius: 12)
                        .fill(Color(UIColor.systemBackground))
                        .padding(.horizontal, 4)
                )
                // 隐藏默认行分隔线
                .listRowSeparator(.hidden)
            }
        }
    }
    .listStyle(InsetGroupedListStyle())
    // 配置列表整体背景突出卡片效果
    .background(Color(UIColor.systemGroupedBackground))
    .scrollContentBackground(.hidden)
}

补充说明

如果你只需要调整行的左右内边距不需要卡片样式,仅需确保listRowInsets加在ForEach内的每个行根视图上,调整对应参数即可生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:24:03