2

I'm trying to construct a vertical grid of strings that have variable lengths to be displayed side by side to each other (such as a collection of social media tags), as follows:

struct ContentView: View {
    let data = ["first text",
    "second text",
    "long text for testing",
    "short",
    "some medium text"
    ]
    let gridItem = GridItem(.adaptive(minimum: 40, maximum: 300))
    var body: some View {
        ScrollView {
            LazyVGrid(columns: [gridItem]) {
                ForEach(data, id:\.self) { item in
                    Text(item)
                        .lineLimit(1)
                        .background(Color.red)
                }
            }
        }
    }
}

but the problem with LazyVGrid is that it's tied to the minimum item width defined in its initializer which doesn't allow it to dynamically adapt to the width of each item.

The result for the above code is:

enter image description here

My question is: how can I display any dynamic list of variable-length strings in a vertically scrollable view in SwiftUI ?

JAHelia
  • 4,684
  • 14
  • 52
  • 102
  • 1
    It is a grid, adaptive but equal grid items. Does this answer your question https://stackoverflow.com/a/58876712/12299030? – Asperi Sep 15 '20 at 17:48
  • it doesn't handle large list of strings, look at this screenshot for that code when it's loaded with about a hundred of strings: https://www.dropbox.com/s/j96az55j786uwgm/lazy%20grid.png?dl=0 – JAHelia Sep 15 '20 at 17:56
  • @Asperi using the second answer here: https://stackoverflow.com/questions/62102647/swiftui-hstack-with-wrap-and-dynamic-height/62103264#62103264 solves the problem and it can handle large number of tags correctly – JAHelia Sep 16 '20 at 07:25

0 Answers0