Set X axis for SwiftUI Chart where X is of type Date?

80 Views Asked by At

I have the following chart:


struct GradientLine: View {
    let data: WeatherStripData
    let elevation: WeatherElevationToggle = .top
    
    var body: some View {
        let dates: [Date] = data.cells.map { cell in
            let date = convertStringToDate(cell.date)!
            return dateByAddingOffset(to: date, hourOffset: stringToInt(cell.weather.time) / 100)
        }

        Chart {
            ForEach(Array(data.cells.enumerated()), id: \.offset) { index, cell in
                let dataPoint = getDataPointAtElevation(
                    elevation: elevation,
                    weather: cell.weather
                )
                LineMark(
                    x: .value("Time", dates[index]),
                    y: .value("Speed", stringToInt(dataPoint.windspeedKmph))
                )
                .interpolationMethod(.catmullRom)
            }
        }
        .chartYAxis {
            AxisMarks(
                position: .leading
            ) { value in
                let value = value.as(Int.self)!
                AxisGridLine()
                AxisTick().foregroundStyle(.clear)
                AxisValueLabel {
                    Text("\(value) km/h")
                }
            }
        }
        .chartXAxis {
            AxisMarks(position: .bottom, values: dates) { value in
                let date = value.as(Date.self)!

                AxisGridLine().foregroundStyle(.clear)
                AxisTick().foregroundStyle(.clear)
                AxisValueLabel {
                    let hour = getHour(from: date)
                    if (hour % 2 == 0){
                        if (hour == 0) {
                            Text(formatDateToName(date)).textCase(.uppercase).bold().fixedSize(horizontal: true, vertical: true)
                        } else {
                            Text("\(formatTime(hour: hour)!)").fixedSize(horizontal: true, vertical: true)
                        }
                    }
                }
            }
        }
        .chartScrollableAxes(.horizontal)
        .frame(height: 150)
    }
}

It currently renders like this:

enter image description here

I would like to only show 1 day per "page" but I can't understand how to use .chartXScale since my X scale is of type Date?

0

There are 0 best solutions below