Is it possible to build a simple collection of flexible Views in SwiftUI using Grid?

649 Views Asked by At

What I'm trying to build is really very simple and common component. Here's the design:

design

Here's the code that I've tried till now:

struct ContentView: View {
    var tags: [String]

    var body: some View {
        LazyVGrid(columns: [GridItem(.flexible(minimum: 0, maximum: .infinity)),
                            GridItem(.flexible(minimum: 0, maximum: .infinity))]) {
            ForEach(tags, id: \.self) { tag in
                Button(action: { print(tag) }) {
                    Text(tag.title)
                        .lineLimit(1)
                        .padding(.vertical, 8)
                        .padding(.horizontal)
                        .overlay(
                            RoundedRectangle(cornerRadius: 4)
                                .stroke(Color.primaryViolet, lineWidth: 2)
                        )
                }
            }
        }
    }
}

Here's what I got:

enter image description here

Here are a few additional details:

  1. Number of tags could vary from 0..<infinity.
  2. Should never get truncated unless a single tag exceeds the entire width of the grid.
  3. Number of tags per row can vary according to the width of tags.
  4. Tags must be left-aligned.

Note: I would prefer a native SwiftUI approach if possible without importing any 3rd party libraries.

0

There are 0 best solutions below