1 year ago

#64672

test-img

Joe Völker

How to get the size of a Text View in SwiftUI w/o rendering the view?

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.

ios

swiftui

swiftui-text

0 Answers

Your Answer

Accepted video resources