SwiftUI LazyVGrid how to size a column to use the greatest width needed to display all its text

Viewed 331

I want to display data in a grid that has a row header with text of different lengths. The width of the first column should be just large enough to fit the longest text. The remaining columns should be equally distributed.

The following sample can be used to illustrate the problem:

struct ContentView: View
{
    private var firstColumn: GridItem { GridItem(alignment: .trailing) }
    private var remainingColumns: [GridItem] { [GridItem(alignment: .center), GridItem(alignment: .center)] }
    private var columns: [GridItem] { [firstColumn] + remainingColumns }
    
    var body: some View {
        LazyVGrid(columns: columns, alignment: .leading) {
            ForEach(1..<5) {row in
                // Row Header
                Text("Row \(row)")
                
                // remaining columns
                ForEach(1..<3) {col in
                    Text("\(row),\(col)")
                }
            }
        }
    }
}

However, for GridItems I can only specify a fixed width or Minimum and Maximum width, but not something like "optimal" width.

Any ideas how to do this?

0 Answers
Related