gpt4 book ai didi

ios - SwiftUI 中的 Gridview

转载 作者:行者123 更新时间:2023-12-03 08:44:40 25 4
gpt4 key购买 nike

我正在尝试在 swiftui 中创建 GridView ,但它不适合我。有人可以告诉我我做错了什么吗?我尝试使用 C 风格的 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())

}


}


}

}
}

}

最佳答案

使用 Array extension to split the list分成更小的组:

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

这可以用来创建类似简单 GridView 的东西,例如:

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

}

关于ios - SwiftUI 中的 Gridview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61946785/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com