Home > Net >  LazyVGrid inside a Picker, using SwiftUI
LazyVGrid inside a Picker, using SwiftUI

Time:12-25

In the code below the picker works great, however the LazyVGrid appears as one column only (should be three columns, as indicated in pickColorTable var).

var pickColorTable:[GridItem] = Array(repeating: .init(.flexible(), spacing: 5), count: 3)

Form {
      LazyVGrid(columns: pickColorTable, spacing: 5) {
          Picker("Color", selection: $pickColor) {
            ForEach(colorTable, id: \.self) { color in
                  Rectangle()
                     .frame(width: 70, height: 70)
                     .foregroundColor(Color(color))
                      .cornerRadius(20)
             }
          }
       }
   }

Image 1

In another hand, if the second line is swapped with the third line, as the code below, LazyVGrid renders correctly, but the picker stops working (nothing happens when I click on the desired color).

 Form {
      Picker("Color", selection: $pickColor) {
          LazyVGrid(columns: pickColorTable, spacing: 5) {
            ForEach(colorTable, id: \.self) { color in
                  Rectangle()
                     .frame(width: 70, height: 70)
                     .foregroundColor(Color(color))
                      .cornerRadius(20)
             }
          }
       }
   }

Image 2

Does anyone have a tip to make LazyVGrid works properly inside the picker?

CodePudding user response:

The problem it appears is that the content of your Picker is a LazyVGrid and not a list of Rectangles. What you can do is add a tap gesture to each rectangle. Then manually mutate the pickColor For instance

Form {
    Picker("Color", selection: $pickColor) {
      LazyVGrid(columns: pickColorTable, spacing: 5) {
            ForEach(colorTable, id: \.self) { color in
              Rectangle()
                .frame(width: 70, height: 70)
                .foregroundColor(Color(color))
                .cornerRadius(20)
                .onTapGesture {
                  pickColor = color
                }
            }
          }
        }
}
  • Related