0

On my content view, I’d like to display a small table. To illustrate: In HTML I’d just say

<table>
    <tr><td>First item</td><td>First value</td></tr>
    <tr><td>Second item</td><td>Second value</td></tr>
    <tr><td>Third item</td><td>Third value</td></tr>
</table>

In SwiftUI, I could do this:

VStack {
    HStack {
        Text("First item")
        Spacer()
        Text("First value")
    }
    HStack {
        Text("Second item")
        Spacer()
        Text("Second value")
    }
    HStack {
        Text("Third item")
        Spacer()
        Text("Third value")
    }
}

However, these HStack()s will use all available space. I want to shrink the table’s width dynamically to the minimum, like HTML would do. I know I can use a LazyVGrid, but then I’d need to compute the column widths by myself.

Looks easy... Just iterate over each rows Text()s, and note the maximum value.

However: There seems to be no easy way to get the dimensions of a view without rendering it first.

I’m lost. Should I render the Text()s in a lonely corner of my View in transparent color to obtain the dimensions?

I feel that this should be easy, and that I’m missing something obvious.

Joe Völker
  • 781
  • 1
  • 5
  • 19
  • `LazyVGrid` columns have an `.adaptive` column width that you can use. You can set a small minimum and let the column size itself. – Yrb Jan 19 '22 at 02:41
  • I’ve tried that. But then, the ```LazyVGrid``` will just wrap around, and put more than 2 items in a row. It seems to understand the data as a one-dimensional entity while a table is two-dimensional by design. – Joe Völker Jan 20 '22 at 06:29
  • I suspect you are supplying the data to the `LazyVGrid()` improperly. If you are concerned about text wrapping, that can be fixed with some modifiers. If you are getting more than 2 items in a row, that is incorrect coding logic. The answer to your question is to use a `LazyVGrid()` with `.adaptive()` column widths. – Yrb Jan 20 '22 at 14:23

0 Answers0