LazyHGrid Equal Distribution

Wish to ask for suggestions. My goal is to have a view where user inputs an array of strings. Depending on the number of strings, should have equal distribution of spacing between them.

E.g. 5 items. 1st item should be top, last item should be bottom while the 2nd-4th should be in between and all of them should have equal spacing.

This is what I have

import SwiftUI

struct MyView: View {
   
  @State private var labels: [String]?

var labels = ["Great", "Major", "Strong", "Moderate", "Small"]
 var colors = [.blue, .red]
   
HStack {
      Spacer()
      LazyHGrid(rows: [GridItem(.adaptive(minimum: 120))]) {
        if let labels {
          Group {
            ForEach(labels, id:\.self) { label in
              Text(label)
            }
          }
        }
      }
      .frame(maxHeight: .infinity)
      Rectangle()
        .foregroundColor(.clear)
        .background(LinearGradient(gradient: Gradient(colors: colors ?? []), startPoint: .top, endPoint: .bottom))
      Spacer()
    }

}

The result is not what I expected it to be. Notice the orange arrows.

If i add more strings, ["Great", "Major", "Strong", "Moderate", "Small", "Great", "Major", "Strong", "Moderate", "Small"], it becomes 2 columns. Why is that?

Maybe because the minimum value si 120? Is there a way to automatically have some formula where the minimum value is set based on the number of strings in the array?

Answered by chitgoks in 734007022

I wanted to make it work with LazyHGrid or LazyVGrid but I decided to go with the simplest one available. Just VStack and put a Spacer() in between.

Accepted Answer

I wanted to make it work with LazyHGrid or LazyVGrid but I decided to go with the simplest one available. Just VStack and put a Spacer() in between.

LazyHGrid Equal Distribution
 
 
Q