我想获取一个可变长度的数组并返回一个包含 3 列和可变行长度的视图网格。视图应该根据数组值更新其内容。
以下代码将为每张卡片呈现一个 CardPicView,在滚动视图中标题为“A”...“I”。
struct ContentView : View {
let cards = ["A", "B", "C", "D", "E", "F", "G", "H", "I"]
var body: some View {
ScrollView {
ForEach(cards.identified(by: \.self)) { card in
CardPicView(cardTitle: card)
}
}
}
}
我想把这个滚动视图本质上分成 3 列。
我发现下面的代码可以使用以下方法创建正确大小的网格:
struct ContentView : View {
let cards = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
var body: some View {
ScrollView{
ForEach(0..<cards.count/3) { row in // create number of rows
HStack {
ForEach(0..<3) { column in // create 3 columns
Text(self.cards[row])
}
}
}
}
}
}
然而,这给了我一个 3x4 网格,其中只有 (AAA/BBB/CCC/DDD)
将其更改为:
struct ContentView : View {
let cards = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L"]
var body: some View {
ScrollView{
ForEach(0..<cards.count/3) { row in // create number of rows
HStack {
ForEach(0..<3) { column in // create 3 columns
Text(self.cards[column])
}
}
}
}
}
}
给我一个只有 (ABC/ABC/ABC/ABC) 的 3x4 网格。
我以某种方式需要使用两个索引迭代行和列,但不知道如何快速执行此操作。