swiftuilayoutgridaspect-ratiolazyvgrid

SwiftUI - How to make grid items fill available space


I am trying to create a 3x4 grid. Each grid item should be the same size. Together the items should fill the entire view (excluding top navigation bar). The grid should be flexible so it stretches or shrinks depending on the size of the view.

So far i have managed to achieve the following: 3x4 grid with square items.  Not scaled to fit view.

This is the code:

struct CustomGrid: View {
    
    let columns = [
        GridItem(.flexible()),
        GridItem(.flexible()),
        GridItem(.flexible())
    ]

    var body: some View {
        ZStack {
            Color.white
            LazyVGrid(columns: columns) {
                ForEach(0..<12) { _ in
                    RoundedRectangle(cornerRadius: 16)
                        .aspectRatio(contentMode: .fit)
                 }
            }
            .padding()
        }
    }
}

This is how i would like the grid to look: 3x4 grid with each item scaled to fit the view

Any help would be greatly appreciated.


Solution

  • I think this should help you

    struct CustomGrid: View {
    
        let numberOfRows: CGFloat = 4
    
        let columns = [
            GridItem(.flexible()),
            GridItem(.flexible()),
            GridItem(.flexible())
        ]
    
        var body: some View {
            ZStack {
                Color.white
                GeometryReader { geo in
                    LazyVGrid(columns: columns) {
                        ForEach(0..<12) { _ in
                            RoundedRectangle(cornerRadius: 16)
                                .frame(height: (geo.size.height / numberOfRows).rounded())
                        }
                    }
                }
                .padding()
            }
        }
    }
    

    You can use GeometryReader to define the height of the screen. And then set the frame height for each RoundedRectangle by determining the height of each element by dividing the screen height by the number of rows. We round up the resulting value, as rendering fractional pixels will greatly affect the rendering engine, and you may encounter lags and frame drops.