2

I'm trying to create a grid view in swiftui and it's not working out for me. Can someone tell me what I'm doing wrong? I tried using a c style for loop where I can set a variable and increment it, but swiftui throws an error when I do that.

struct ProductSubCat: View {

    @State var productCategory = String()
    @State var number = Int()
    @ObservedObject var allData = WebserviceGetDataSolutions()
    @State var theCount = 0



    var body: some View {

                ScrollView {
                    Spacer()

                    ForEach(0 ..< self.allData.posts[self.number].productLines.count / 2, id: \.self) {row in

                        HStack {
                            ForEach(0..<2) {cell in
                                NavigationLink(destination: ProductDetails())
                                {
                                    Text(self.allData.posts[self.number].productLines[row].system)

                                   Image("stonclad")
                                   .resizable()
                                   .aspectRatio(contentMode: .fit)



                                }.buttonStyle(PlainButtonStyle())

                            }


                        }


                    }

        }   
        }

    }
3

1 Answer 1

6

Use an Array extension to split the list into smaller groups of size:

extension Array {
    func chunks(_ size: Int) -> [[Element]] {
        stride(from: 0, to: self.count, by: size).map { ($0 ..< Swift.min($0 + size, self.count)).map { self[$0] } }
    }
}

This can then be used to create something like a simple grid View, for example:

struct Product: Identifiable, Hashable {
    var id = UUID()
    var name: String
}

struct SimpleGridViewExample: View {

    var products = [Product(name: "p1"), Product(name: "p2"), Product(name: "p3"), Product(name: "p4"), Product(name: "p5")]

    var body: some View {
        ScrollView {
            VStack(alignment: .leading) {
                ForEach(products.chunks(2), id: \.self) { chunk in
                    HStack {
                        ForEach(chunk, id: \.self) { product in
                            VStack {
                                Image(systemName: "sun.max")
                                    .resizable()
                                    .frame(maxWidth: 100, maxHeight: 100)
                                    .aspectRatio(contentMode: .fit)
                                Text(product.name)
                            }
                        }
                    }
                }
            }
        }
    }

}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.