swiftuigrid-layoutrow-height

How to make SwiftUI LazyGrid rows set heights according to contents, independently


I have an array of text items with varying amounts of text in them. I want to display them as rows of line number and text with boxes around number and txt separately. The catch is I want the box around the number to be the same height as the box around the text.

I found this question and answer which almost makes it, except every line is the same height, ie sized to the largest visible row. I want each row to be sized according to its own text size, ie each row might be a different height.

I tried changing the lazy grid to a VStack (there's unlikely to be more than forty rows) so that the sizing wasn't limited to visible rows, but then I couldn't get height or width to cooperate.

Is there a way?


Solution

  • As @Yrb suggests a solution (which seems to me the simplest) is to modify the answer I linked by creating a struct for the rows and then moving the height calculating extension to extend that struct rather than the entire view.

    This beautifully calculates the height of each row independently of the others.