swift 快速图表:为什么这不是并排的条形图?

nmpmafwu  于 2023-03-28  发布在  Swift
关注(0)|答案(1)|浏览(132)
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
        
    }

}

vq8itlhq

vq8itlhq1#

它一定与我的xAxis有关,因为添加了以下代码,使XAxis成为一周中的一天,并按照我的要求并排对齐条形图:

.chartXAxis {
            AxisMarks (values: .stride (by: .day)) { value in
                AxisValueLabel(format: .dateTime.weekday(),
                               centered: true)
            }
        }

相关问题