Reading time: 1 min

This quick recipe shows how to convert AxisValue to a Text using Apple's new Charts Framework.

The end result looks like this:

Screenshot%202022-06-20%20at%2020.02.01

Charts framework is available starting in SwiftUI 4 (iOS 16, macOS 12.4).

When you construct X or Y axis in SwiftUI charts using chartXAxis or chartYAxis, you usually pass the AxisMarks result builder. It provides its block with an AxisValue instance the represents the current axis mark. However, it only knows its index and total count - but not its actual value.

The key is to cast the value to a primitive with as(:) method. The example below plots integers on the Y axis, so cast to Int.self is correct:

Chart {
  // ...
}
.chartYAxis {
  AxisMarks(values: .automatic) { value in
    AxisGridLine(centered: true, stroke: StrokeStyle(dash: [1, 2]))
      .foregroundStyle(Color.cyan)
    AxisTick(centered: true, stroke: StrokeStyle(lineWidth: 2))
      .foregroundStyle(Color.red)
    AxisValueLabel() {
      if let intValue = value.as(Int.self) { // HERE
        Text("\(intValue) km")
          .font(.system(size: 10))
          .foregroundColor(.blue)
        }
    }
  }
}

Next Post Previous Post