2

I would like to create a grid with 24 Items in 4 rows, so each row should have 6 items. All items should be equally sized but fill the whole space available, no matter what device the grid is rendered on.

I already achieved a flexible height for the rows, but the GridItems do not push put in horizontal dimension, although it is a shape, that is said to be pushing out. Well within a LazyHGrid it seems not to push out.

This is my code:

struct AllAchievementsView: View {
    
    var gridRows: Array<GridItem>  { [GridItem(), GridItem(), GridItem(), GridItem()] }

    var body: some View {
        
        ZStack {
            Color.black
            LazyHGrid(rows: gridRows) {
                ForEach(0..<24) { index in
                    RoundedRectangle(cornerRadius: 10).foregroundColor(.blue)
                }
            }.padding()
        }
    }
}

I tried all variants on GridItem sizing, I tried to add a frame on my Rectangle with .infity, etc. couldn't realize it. Do I really have to make the math programmatically with a GeometryReader?

I add two images: One shows the result of this code, the other shows, what I want to realize.

Current result of the code

Expected

pawello2222
  • 23,992
  • 12
  • 59
  • 94
LukeSideWalker
  • 5,686
  • 2
  • 25
  • 38
  • 1
    Are you not simply missing the `aspectRatio(1, contentMode: .fit)` modifier? Personally I do not like the solution relying on `GeometryReader`. Depending on your requirements, you can simply set an aspect ration of 16/10 or 1/1 on your `RoundedRectangle` to ensure it does have a reasonable width. – pd95 Jan 05 '21 at 22:25

1 Answers1

2

The GridItem is filled/aligned according to the size of content, but the Rectangle has no own size, so you see used some minimum default values.

Here is a possible solution (tested with Xcode 12 / iOS 14)

enter image description here

struct AllAchievementsView: View {
    
    let sp = CGFloat(5)
    var gridRows: Array<GridItem> { Array(repeating: GridItem(spacing: sp), count: 4) }

    var body: some View {
        
        GeometryReader { gp in
            ZStack {
                    Color.black
                    LazyHGrid(rows: gridRows, spacing: sp) {
                         ForEach(0..<24) { index in
                              RoundedRectangle(cornerRadius: 10).foregroundColor(.blue)
                                .frame(width: gp.size.width / 6 - 2*sp)
                         }
                    }
                    .padding()
            }
        }
    }
}
Asperi
  • 123,447
  • 8
  • 131
  • 245