我尝试使用网格布局的这种解决方案。
我们希望在 Grid 中动态显示 Array Items,如果 Array.count Changed 出现 Index out of Range 错误并且应用程序崩溃。
如何解决这个问题?
var totalrows: Int{
let t = Double(self.cards.count) / Double(self.cols)
return Int(round(t))
}
var cols: Int{
let col = self.verticalSizeClass == .compact ? 4 : 2
return col
}
func colrow (col: Int , row: Int) -> Int{
var colrow = 0
colrow = (row * self.cols) + col
return colrow
}
let cards = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M"]
var body: some View {
VStack{
ForEach(0..<self.totalrows,id:\.self) { row in
HStack {
ForEach(0..<self.cols,id:\.self) { column in
Text(self.cards[self.colrow(col: column, row: row)])
}
}
}
}
}