我需要访问索引以及 ForEach 循环中的元素。
到目前为止,我的数据存储中有:
@Published var sevenDayReview: [[CGFloat]] = [
[1754,1654],[1854,1687],[1985,1854],[1765,1652],[1864,1698],[1987,1654],[1865,1465]
]
在我看来:
ForEach(self.dataModel.sevenDayReview, id: \.self) { array in
ForEach(array, id: \.self) { element in
VStack {
ReviewChart(dataModel: CalorieViewModel(), valueHeight: element, cornerRadius: 5, color: 2 )
}
}
}
工作正常。但我想将当前元素的当前数组索引传递给 color 参数。
背景:使用数据存储中的值加载条形图,并按行索引交替颜色。
我不知道在 SwiftUI 中执行此操作的最佳方法是什么。
最佳答案
您可以使用different init ForEach View 的:
ForEach(0..<array.endIndex) { index in //inner ForEach
VStack {
ReviewChart(dataModel: CalorieViewModel(),
valueHeight: array[index],
cornerRadius: 5,
color: index)
}
}
关于SwiftUI ForEach 获取二维数组中的元素和索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59734553/