Search code examples
xcodeswiftuilazyhgrid

Problem with formatting LazyHGrid - SwiftUI


I am trying to create a basic lazyHGrid but after looking at a couple of different tutorials online I still can't manage to build it properly. I am trying to make a grid that is filled with rectangles with symbols and text inside those rectangles. See image below:

enter image description here

If I make this in a HStack all the rectangles are presented correctly, but as soon as I put it into a LazyHGrid I get this problem. Any ideas?

let rows = [
            GridItem(.fixed(200)),
            GridItem(.fixed(200)),
        ]
    
    var product: ProductModel

    var body: some View {
        LazyHGrid(rows: rows, alignment: .center) {
            ForEach(0..<product.imageStack01Image.count, id: \.self) { item in
                ZStack(alignment: .top){
                    RoundedRectangle(cornerRadius: 25, style: .continuous)
                        .fill(Color.white)
                        .frame(width: 200, height: 200)
                        .shadow(color: Color.black.opacity(0.08), radius: 20, x: 0, y: 5)
                    VStack(alignment: .leading) {
                        Image(systemName:product.imageStack01Image[item])
                            .font(.system(size: 40.0))
                            .frame(height: 40)
                            .foregroundColor(.red)
                            .padding(.top, 40)
                            .padding(.leading, 10)
                        Text(product.imageStack01Text[item])
                            .font(.title2)
                            .fontWeight(.medium)
                            .multilineTextAlignment(.trailing)
                            .padding(10)
                        
                    }
                }
            }
        }
    }

Solution

  • As far as I understood your try to put image and text into rectangle, so try to use overlay instead of ZStack

        ForEach(0..<product.imageStack01Image.count, id: \.self) { item in
            RoundedRectangle(cornerRadius: 25, style: .continuous)
                .fill(Color.white)
                .frame(width: 200, height: 200)
                .shadow(color: Color.black.opacity(0.08), radius: 20, x: 0, y: 5)
                .overlay(
                    VStack(alignment: .leading) {
                        Image(systemName:product.imageStack01Image[item])
                            .font(.system(size: 40.0))
                            .frame(height: 40)
                            .foregroundColor(.red)
                            .padding(.top, 40)
                            .padding(.leading, 10)
                        Text(product.imageStack01Text[item])
                            .font(.title2)
                            .fontWeight(.medium)
                            .multilineTextAlignment(.trailing)
                            .padding(10)
                })
            }
        }