SwiftUI LazyVGrid 间距未按预期工作

SwiftUI LazyVGrid spacing not working as expected

以下生成的网格没有垂直间距(正确),但网格中每个项目之间的水平间距为 20 像素。我究竟做错了什么?我不希望项目之间有任何间距。

private var columnGrid: [GridItem] = Array(repeating: .init(.flexible(), spacing: 0), count: 15)

var body: some View {
    LazyVGrid(columns: columnGrid, spacing: 0) {
        ForEach(Array(viewModel.array.enumerated()), id: \.offset) { character in
            SomeView(char: character.element)
                .background(.red)
        }
    }
    .background(.green)
}

您的 SomeView() 内容似乎没有占用所有可用内容 space。您可以在其中的某处使用:

.frame(maxWidth: .infinity)

这是演示:

    private var columnGrid: [GridItem] = Array(repeating: .init(.flexible(), spacing: 0), count: 15)

    var body: some View {
        LazyVGrid(columns: columnGrid, spacing: 0) {
            ForEach(0..<40) { character in
                Text("\(character)")
                    .frame(height: 50)
                    .frame(maxWidth: .infinity) // here
                    .border(.primary, width: 1)
                    .background(.gray)
            }
        }
        .background(.green)
        .padding()
    }