SwiftUI LazyHGrid, LazyVGrid

29 Views Asked by At

I have tags side by side in SwiftUI with different widths. When they don't fit side by side, I want them to wrap to the next line. I tried using LazyHGrid and LazyVGrid for this.

Here is a bit of my code:

struct ContentView: View {
    let rows = [
        GridItem(.flexible())
    ]
    
    var body: some View {
        ScrollView {
            LazyHGrid(rows: rows,
                      alignment: .firstTextBaseline,
                      spacing: 10) {
                HStack {
                    tags("Example")
                    tags("Example long text")
                    tags("Example text")
                }
            }
        }
    }
    private func tags(_ text: String) -> some View {
        Text(text)
            .padding()
            .background(Color.accentColor)
            .cornerRadius(30)
    }
}

The output looks like this: click

But I want it to go to the bottom line like this: click

​ What's the cleanest way to do this?

I saw this answer. How can I do it differently? https://stackoverflow.com/questions/58842453/swiftui-hstack-with-wrap#:~:text=Here%20is%20some,is%20the%20result%3A

0

There are 0 best solutions below