【问题标题】:Gridview in SwiftUISwiftUI 中的网格视图
【发布时间】:2020-09-08 19:23:31
【问题描述】:

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

                            }


                        }


                    }

        }   
        }

    }

【问题讨论】:

标签: ios swift xcode swiftui swift5


【解决方案1】:

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

这可以用来创建一个简单的网格视图,例如:

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-17
    • 1970-01-01
    相关资源
    最近更新 更多