Search code examples
swiftuialignmentlazyvgrid

SwiftUI LazyVGrid - align top


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?


Solution

  • 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)