Core Data @FetchRequest SwiftUI

问题描述 投票:0回答:1

我正在尝试在SwiftUI Charts包/ CocoaPod中使用提取请求。我的问题是,当我使用ForEach遍历属性(ACFTScores.totalScore)时,它会在每个图表中填充一个值...我知道这是因为BarChart位于ForEach的正文中,但我不知道如何抓取范围并使其与SwiftUI图表一起使用。

enter image description here

struct DashboardACFT: View {
    @FetchRequest(entity: ACFTScores.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \ACFTScores.totalScore, ascending: true)]) var acftScores: FetchedResults<ACFTScores>

    var body: some View {
        VStack {
            ForEach(acftScores, id: \.id) { score in
                BarChartView(data: [Int(score.totalScore)], title: "Title", legend: "Legendary")
            }
        }
    }
}
core-data swiftui nsfetchrequest
1个回答
0
投票

我尚未使用图表,但是您需要将获取请求映射到包含要在图表中使用的值的数组。像这样的东西

var body: some View {
    VStack {
        BarChartView(data: acftScores.map {$0.totalScore}, title: "Title", legend: "Legendary")
        }
    }
}

由于您出于某种原因似乎需要使用Int将属性转换为compactMap可能更好。

acftScores.compactMap {Int($0.totalScore)}
© www.soinside.com 2019 - 2024. All rights reserved.