there is one logic error. Let's say i have five devices in chart: device 1 with count of…
- User
there is one logic error. Let's say i have five devices in chart:
device 1 with count of 10 device 2 with count of 7 device 3 with count of 5 device 4 with count of 2 device 5 with count of 1
now, if i generate a new device serial called device 6 with count of 3, the chart goes messy, as the device 5 is not removed from the chart
import SwiftUI import Charts
struct TotalSerialsView: View { @EnvironmentObject var serialHistory: SerialHistory @State private var selectedTimeframe: Timeframe = .today
func modelFromAxisValue(for value: AxisValue) -> Model? { guard let modelName = value.as(String.self) else { return nil } return serialHistory.topModelCounts.first(where: { $0.model.name == modelName })?.model } var body: some View { VStack(alignment: .leading) { Picker("Periood", selection: $selectedTimeframe) { Text("Täna").tag(Timeframe.today) Text("See nädal").tag(Timeframe.week) Text("See kuu").tag(Timeframe.month) Text("See aasta").tag(Timeframe.year) } .pickerStyle(.segmented) .padding(.bottom, 10) Text("Genereeritud seerianumbreid") .font(.subheadline) .foregroundStyle(.secondary) Text("\(serialHistory.records.count) seerianumbrit") .font(.headline) // Display chart deviceChart } .padding() } var deviceChart: some View { Chart { ForEach(serialHistory.topModelCounts) { modelCount in BarMark( x: .value("Device", modelCount.model.name), y: .value("Count", modelCount.count) ) .cornerRadius(6, style: .continuous) .foregroundStyle(.linearGradient(colors: [Color("BarBottomColor"), .accentColor], startPoint: .bottom, endPoint: .top)) .annotation(position: .top) { Text("\(modelCount.count)") .font(.caption) } } } .chartYAxis { AxisMarks(preset: .automatic) { _ in AxisGridLine() AxisTick() AxisValueLabel() } } .chartXAxis { AxisMarks(values: .automatic) { value in AxisValueLabel { if let model = modelFromAxisValue(for: value) { VStack { Text(model.modelNumber) .lineLimit(2) .multilineTextAlignment(.center) } .frame(idealWidth: 80) .padding(.horizontal, 4) } else { // Fallback content if the model is nil Text("Unknown") .font(.caption) } } } } }}
struct TotalSerialsView_Previews: PreviewProvider { static var previews: some View { TotalSerialsView() .environmentObject(SerialHistory()) } }
extension SerialHistory { var topModelCounts: [ModelCount] { let sortedCounts = modelCounts.sorted { 1.count } return Array(sortedCounts.prefix(5)) } }
- Assistant