SwiftUI 中的 Gridview

C.J*_*nes 2 xcode ios swift swift5 swiftui

我正在尝试在 swiftui 中创建网格视图,但它不适合我。有人可以告诉我我做错了什么吗?我尝试使用 ac 风格的 for 循环,我可以在其中设置变量并递增它,但是当我这样做时 swiftui 会抛出错误。

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())

                            }


                        }


                    }

        }   
        }

    }
Run Code Online (Sandbox Code Playgroud)

Ral*_*ert 5

使用数组扩展将列表分成较小的组:

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] } }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后可以使用它来创建类似简单网格视图的内容,例如:

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)
                            }
                        }
                    }
                }
            }
        }
    }

}
Run Code Online (Sandbox Code Playgroud)