Allow Adaptive Cells to Expand To Fill Height in GridView (SwiftUI)

Viewed 30

Problem

I have a GridView, it has some cells with a fixed height, and some that are adaptive.. In a row where there are FixedHeight cells, I'd like the AdaptiveHeight cells to be tall as the tallest FixedHeight cell.

Goal

In this example, I'd like the black cells to be as tall as the red cell in row0, and the purple cell in row1.

resulting gridview

Example

Here is some reproducible code:

import SwiftUI

var farbe: [Color] = [
    .red, .orange, .yellow, .blue, .purple, .pink, .gray
]

struct Cell: View {
    let color: Color
    
    var body: some View {
        Rectangle().fill(color)
    }
}

struct GridTest: View {
    let columns = [
        GridItem(.fixed(20), spacing: 20, alignment: .top),
        GridItem(.adaptive(minimum: 80, maximum: .infinity), alignment: .top),
    ]
    
    var body: some View {
        LazyVGrid(columns: columns, alignment: .leading, spacing: 12) {
            ForEach(1...9, id: \.self) { idx in
                if idx % 3 == 1 {
                    let color = farbe.randomElement()!
                    Cell(color: color)
                        .frame(height: CGFloat(idx) * 12)
                        .border(Color.black, width: 2)
                } else {
                    Cell(color: .black)
                        .border(Color(.systemGray6), width: 2)
                }
            }
        }
        .background(Color(.systemGray2))
    }
}

struct GridTest_Previews: PreviewProvider {
    static var previews: some View {
        GridTest()
    }
}
0 Answers
Related