enum SwiftChartEnergyType {
case Burned
case Consumed
}
struct SwiftChartEnergyObject: Identifiable {
let id = UUID()
let energy: Int
let date: Date
var swiftChartEnergyType: SwiftChartEnergyType
}
@available(iOS 16.0, *)
struct WeeklyEnergyGroupSWIFTBarChart: View {
var energyDays: [EnergyDay] = []
var dietaryDays: [DietaryDay] = []
var body: some View {
VStack {
Chart(prepareDatForChart(), id: \.energyType) { item in
ForEach(item.data) {
BarMark(
x: .value("Date", $0.date),
y: .value("Energy", $0.energy)
)
.foregroundStyle(by: .value("Energy Type", item.energyType))
.position(by: .value("Energy Type", item.energyType)) // << why is this not placing the bars side by side as a "grouped bar chart?"
}
}
.chartYAxis {
AxisMarks(position: .leading)
}
.chartForegroundStyleScale([
"Burned" : TrackerConstants.AppleFitnessOrange,
"Consumed": TrackerConstants.AppleFitnessGreen
])
}
}
private func prepareDatForChart() -> [(energyType: String, data: [SwiftChartEnergyObject])] {
let data = [
(energyType: "Burned", data: energyDays.map { SwiftChartEnergyObject(energy: $0.totalEnergyBurned, date: $0.date, swiftChartEnergyType: .Burned) } ),
(energyType: "Consumed", data: dietaryDays.map { SwiftChartEnergyObject(energy: $0.totalCalories, date: $0.date, swiftChartEnergyType: .Consumed) } )
]
return data
}
}
1条答案
按热度按时间vq8itlhq1#
它一定与我的xAxis有关,因为添加了以下代码,使XAxis成为一周中的一天,并按照我的要求并排对齐条形图: