1

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.

Frankenstein
  • 13,516
  • 4
  • 12
  • 38
  • Have you tried using Adaptive instead of flexible? If I am correct you need as many grid in one row as possible? – Tushar Sharma Apr 27 '21 at 16:17
  • @TusharSharma Posted here after trying a few different approaches and failed. Something so common should be simple to implement. – Frankenstein Apr 27 '21 at 16:31
  • `LazyVGrid` might not fit your needs. What you are looking for is a `UICollectionView` SwiftUI alternative, but unfortunately even SwiftUI 2 doesn't have a built-in view that would handle all features of `UICollectionView`. Have a look at [this](https://stackoverflow.com/questions/62102647/swiftui-hstack-with-wrap-and-dynamic-height/62103264#62103264) answer though, it should fully fit your needs. – Dávid Pásztor Apr 27 '21 at 16:47

0 Answers0