swift - SwiftUI 网格索引超出范围
问题描述
我尝试使用网格布局的这种解决方案。
我们希望在 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)])
}
}
}
}
}
解决方案
避免任何 indexOutOfBounds 的一种简单方法是在执行操作之前检查索引是否超出范围......
所以做这个改变:
ForEach(0..<self.cols,id:\.self) { column in
let card = self.colrow(col: column, row: row)
if (card < self.cards.count) {
Text(self.cards[card])
}
}
这将使您的最后一行可能未填充,但不应崩溃
推荐阅读
- javascript - 如何在javascript中绑定多个函数?
- python-3.x - 如何在 Python 3 中获取向量输入?
- javascript - 每当单击新表格行时如何打开新窗口React?
- android - lateinit 属性 newTrack 尚未初始化
- excel - 如何在 Excel 中重新组织串联项目?
- php - 基于非整数列的 Laravel 模式
- google-chrome - 托管在 IIS 中的 vue-cli 应用程序。缓存问题
- r - 在聚合中为粘贴功能设置折叠
- python - 如何通过python 3.7中的数据框列表迭代函数
- python - 如何添加或删除数量购物车 django 以及模板?