Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 415
DevB1 Avatar asked Sep 14 '25 14:09

DevB1


1 Answers

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)

like image 192
Asperi Avatar answered Sep 16 '25 04:09

Asperi