0

There are three columns, if you look at the images the cells' y axis placement is row dependent. For example, regardless of the height of each image/cell the cells are spaced so that the row maintains alignment with its adjacent cells left and right. This creates awkward vertical white space. I want the cells to move up or down based on the vertical spacial allowance not creating white space in order to row-align with its neighbors. I like that LazyGrid loads the cells dynamically and reuses them.

enter image description here

Here is my code:


import SwiftUI

struct ContentView: View {

    private var symbols = ["keyboard", "hifispeaker.fill", "printer.fill", "tv.fill", "desktopcomputer", "headphones", "tv.music.note", "mic", "plus.bubble", "video"]

    private var colors: [Color] = [.yellow, .purple, .green]

    var body: some View {
        ScrollView {
            LazyVGrid(columns: .init(3), alignment: .center, spacing: 10) {
                ForEach((0...999), id: \.self) {
                    Image(systemName: symbols[$0 % symbols.count])
                        .font(.system(size: 30))
                        .frame(width: 50, height: CGFloat.random(in: 0...100))
                        .background(colors[$0 % colors.count])
                        .cornerRadius(10)
                }
            }
        }
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

extension Array where Element == GridItem {
    init(_ count: Int) {
        self = Array(repeating: GridItem(.flexible()), count: count)
    }
}
ScottyBlades
  • 12,189
  • 5
  • 77
  • 85
  • I might be misinterpreting your question, but I don't think this is possible with a `LazyVGrid` -- if you don't have row/column alignment, it's no longer a 'grid'. – jnpdx Apr 14 '21 at 19:58
  • you cannot do that with `LazyVGrid`, impossible!, but you can make it possible in custom way. – ios coder Apr 14 '21 at 20:12
  • Okay, I edited the title. I am not married to LazyVGrid. How can I do that? – ScottyBlades Apr 14 '21 at 20:29
  • you can do with 3 side by side VStack/LazyVStack, that would be your answer – ios coder Apr 14 '21 at 21:48
  • I'm having trouble imagining that. In a VStack wouldn't the content flow horizontally? Also would all the content scroll together if I had separate LazyVStacks? – ScottyBlades Apr 14 '21 at 22:13
  • 1
    You said yourself, **"VStack"**, V = Vertical, VStack is a vertical Stack the content organised vertically. – ios coder Apr 14 '21 at 22:42
  • This should be helpful https://stackoverflow.com/a/62103264/12299030. – Asperi Apr 15 '21 at 08:15

0 Answers0