Home > Mobile >  Align LazyVGrid columns to the top
Align LazyVGrid columns to the top

Time:02-03

I have a TabView with a LazyVGrid. Attempting to align my items to the top of the view. When I scroll to the next page, would like the items to also align to the top. As of now the items are appearing directly in the middle of the View.

enter image description here

             TabView {
                   ForEach(Array(rm.recipes.chunked(into: 4)), id: \.self) { recipesChunk in
                       LazyVGrid(columns: columns) {
                          ForEach(recipesChunk, id: \.id) { recipe in
                             Text("Test")
                          }
                       }
                   }
               }
           .tabViewStyle(.page)
           .gesture(
               DragGesture()
                  .onEnded { value in
                      if value.translation.width < 0 {
                          self.currentPage = min(self.currentPage   1, rm.recipes.count / 4)
                  } else if value.translation.width > 0 {
                      self.currentPage = max(self.currentPage - 1, 0)
                  }
              }
            )

CodePudding user response:

You need to set a specific height and alignment for your LazyVGrid.

Like this:

struct ContentView: View {
    var data: Array<Array<String>> {
        let data0 = ["1", "2"]
        let data1 = ["3"]
        return [data0, data1]
    }

    let columns = Array(repeating: GridItem(.flexible(), spacing: 6), count: 1)

    var body: some View {
        TabView() {
            ForEach(data, id: \.self) { data in
                LazyVGrid(columns: columns, spacing: 50) {
                    ForEach(data, id: \.self) { data in
                        Text(data)
                    }
                }.frame(height: 50, alignment: .top) // <- HERE
            }
        }.tabViewStyle(.page)
    }
}

enter image description here

  • Related