2

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

Paul
  • 1,101
  • 1
  • 11
  • 20
  • 1
    Does this answer your question https://stackoverflow.com/a/63027052/12299030? – Asperi Dec 01 '21 at 18:25
  • Hmm, seems like I'll have to use `LazyVGrid`? I tried it with the `LazyHGrid` and the results didn't render. :( I can try it with `LazyVGrid` and loop back – Paul Dec 02 '21 at 01:42

1 Answers1

0

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

Paul
  • 1,101
  • 1
  • 11
  • 20