SwiftUI ForEach 获取二维数组中的元素和索引

标签 swiftui

我需要访问索引以及 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/

相关文章:

SwiftUI 核心数据,分组列表获取结果

使用 Sqlite 和 GRDB 的 SwiftUI FileDocument

swift - 使用工具栏按钮折叠 SwiftUI 右侧边栏

swift - 添加枚举后失去了对 Codable 的一致性

ios - SwiftUI macos NSWindow 实例

SwiftUI 多窗口关闭会导致崩溃

具有绑定(bind)变量的 SwiftUI 预览提供程序

ios - 如何在 HStack 中始终位于中心的 Spacers 之间创建 View ?

swift - 如何在 SwiftUI 中绘制圆的径向切片? (即饼状图)

ios - 如何从 SwiftUI View 返回到 UIKit?