How to reduce space between LazyHGrid rows?

Viewed 195

I'm using GridItem and LazyHGrid to create a Calendar like view. I followed this post in an attempt to reduce the space between rows in my LazyHGrid but the spacing between rows do not shrink. I believe I am missing a concept about using grid layout in SwiftUI.

How can I reduce the space between my Week views in LazyHGrid?

struct Week: View {
    var startDay: Int
    var endDay: Int

    var rows: [GridItem] = [
        GridItem()
    ]

    var body: some View {
        ScrollView(.horizontal) {
            LazyHGrid(rows: rows, alignment: .top, spacing: 50) {
                ForEach((startDay...endDay), id: \.self) { dayOfWeek in
                    Text("\(dayOfWeek)")
                        .font(.system(size: 20, weight: .semibold))
                }
            }
            .padding()
        }
    }

}

struct Calendar: View {

    var rows: [GridItem] = [
        GridItem(spacing: 2),
        GridItem(spacing: 2),
        GridItem(spacing: 2),
        GridItem(spacing: 2)
    ]

    var body: some View {
        ScrollView(.horizontal) {
            LazyHGrid(rows: rows, alignment: .top) {
                ForEach((1...4), id: \.self) { _ in
                    Week(startDay: 1, endDay: 7)
                }
            }
            .frame(width: .infinity, height: 450)
        }
    }
}

enter image description here

1 Answers

I was thinking about this incorrectly. You can create a LazyVGrid with 7 columns and then just have a ForEach loop that creates 30 different views which will wrap around to become rows.

struct Calendar: View {

    // create 7 columns
    var cols: [GridItem] = [
        GridItem(spacing: 50),
        GridItem(spacing: 50),
        GridItem(spacing: 50),
        GridItem(spacing: 50),
        GridItem(spacing: 50),
        GridItem(spacing: 50),
        GridItem(spacing: 50)
    ]

    var body: some View {
        LazyVGrid(columns: cols, spacing: 5) {
            ForEach((1...30), id: \.self) { num in
                Text("\(num)")
            }
        }
        .frame(width: .infinity, height: 450)
        .padding()
    }
}

enter image description here

Related