12

I have a load of cards which I need to display in a vGrid. However, the cards have dynamic heights and what I want to do is have the cards in the columns align to the top.

This is the current setup:

let resultGridLayout = [GridItem(.adaptive(minimum: 160), spacing: 10)]

func itemsView() -> some View {
        VStack {
            filterButton()
                .padding(.bottom)
            LazyVGrid(columns: resultGridLayout, spacing: Constants.ItemsGrid.spacing) {
                ForEach(MockData.resultsData, id: \.id) { result in
                    ProductCardView(viewModel: .init(container: viewModel.container, menuItem: result))
                }
            }
            .padding(.horizontal, Constants.ItemsGrid.padding)
        }
    }

Here is how the layout currently is:

enter image description here

So each item is being centered in it's column space, whereas what I want to happen is for them to align across the top of each row.

Obviously the alignment modifier for vGrid allows us to align horizontally (.center, .leading, .trailing etc) but how can I stop these being aligned vertically in the centre?

DevB1
  • 1,235
  • 3
  • 17
  • 43
  • You are going to have to have `ProductCardView` standardize Its height, and then align the cards in it to the top. I would otherwise suggest a preference key solution, but the LazyVGrid prevents that from being effective as not all the views are rendered, and thus can't be read so the height becomes variable as the view is scrolled. – Yrb May 11 '22 at 02:24

1 Answers1

25

I assume you wanted to align grid item itself, like

let resultGridLayout = [GridItem(.adaptive(minimum: 160), spacing: 10, 
                          alignment: .top)]    // << here !!

demo

Tested with Xcode 13.3 / iOS 15.4 (on some replication)

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Asperi
  • 228,894
  • 20
  • 464
  • 690