I'm using SwiftUI Charts and having issues displaying labels

39 views Asked by At

For some reason this code won't show any labels:

.chartXAxis {
    AxisMarks(position: .bottom, values: viewModel.timeStamps()) { value in
        if let txt = viewModel.dateText(index: value.index) {
            
            AxisValueLabel() {
                Text(txt)
            }
            AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5))
            AxisTick(stroke: StrokeStyle(lineWidth: 0.5))
        }
    }
}

... but this will:

.chartXAxis {
    AxisMarks(position: .bottom, values: .automatic(desiredCount: viewModel.timeStamps().count)) { value in
        if let txt = viewModel.dateText(index: value.index) {
            
            AxisValueLabel() {
                Text(txt)
            }
            AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5))
            AxisTick(stroke: StrokeStyle(lineWidth: 0.5))
        }
    }
}

For whatever reason, even though the count is 69 in this instance, debugging repeats the indices 1-5, when I do a breakpoint and I never see an index of 6-68, so I'm lost here.

I tried a number of ways of changing the index, to no avail.

-- Update

After doing a bit of reading up, I discovered automatic was trying to interpret data automatically but failing, and the explicit values needed more instruction:

    .chartXAxis {
        AxisMarks(preset: .extended, position: .bottom, values: viewModel.entries().indices.filter { $0 % viewModel.selectedTimeSeries.stride() == 0 }) { value in
            if let index = value.as(Int.self), let txt = viewModel.dateText(index: index) {
                
                AxisValueLabel() {
                    Text(txt)
                }
                AxisGridLine(stroke: StrokeStyle(lineWidth: 0.5))
                AxisTick(stroke: StrokeStyle(lineWidth: 0.5))
            }
        }
    }
0

There are 0 answers