首页 > 解决方案 > ForEach 循环查看而不是图表数据

问题描述

我正在尝试ForEach填充数据。显然,这只是按预期创建了一个带有一个 dataPoint 的新视图。如何注入阵列?

我在 ViewBuilder 之外尝试@State了一个for-in循环,但由于某种原因这不起作用。

struct DashboardView: View {
    @ObservedObject var scoreListVM = ScoreListViewModel()
    @State private var isPresented = false
    var body: some View {
        NavigationView {
            VStack {
                ForEach(scoreListVM.scoreCellViewModels) { scoreListVM in
                    LineView(data: [Double(scoreListVM.score.totalScore)], title: "Acft Scores")
                }
            }
            .navigationBarTitle("Dashboard")
            .navigationBarItems(trailing:
                Button(action: {
                    self.isPresented.toggle()
                }) {                    
                    Image(systemName: "book.circle")
                        .imageScale(.medium)
                }
                .sheet(isPresented: $isPresented) {
                    InstructionView()
                        .environmentObject(self.colorSchemes)
            })
        }
    }
}

标签: swiftforeachswiftui

解决方案


如果您希望ForEach循环创建许多LineView项目,则可以使用动态ForEach(带有显式id):

ForEach(scoreListVM.scoreCellViewModels, id:\.self) { scoreCellVM in
    LineView(data: [Double(scoreCellVM.score.totalScore)], title: "Acft Scores")
}

假设scoreListVM.scoreCellViewModels变量是一个ScoreCellViewModel项目数组。


推荐阅读