图表:如何在 LineChartView 中设置左右轴标签的颜色?

Charts: How to set colors of left and right axis labels in LineChartView?

我的图表使用自定义 IAxisValueFormatters 设置左右轴标签(如下)。我试过在左轴和右轴(如下)上使用 labelTextColor 属性,但它们没有改变标签的字体颜色。

class myViewController {

    func initalizeGraph() {

        //omitted for brevity

        let leftYAxisValueFormatter = SpeedAndHRLeftYAxisValueFormatter(measurementSystem: measurementSystem)
        lineChartView.leftAxis.labelTextColor = iPhoneThemeColor1
        lineChartView.leftAxis.valueFormatter = leftYAxisValueFormatter

        let rightYAxisValueFormatter = SpeedAndHRRightYAxisValueFormatter()
        lineChartView.rightAxis.labelTextColor = iPhoneThemeColor2
        lineChartView.rightAxis.valueFormatter = rightYAxisValueFormatter
    }
}

class SpeedAndHRLeftYAxisValueFormatter: IAxisValueFormatter {
    //left side is speed

    //multiplu value x 40 (.5 * x = 20?)
    var measurementSystem: MeasurementSystem

    init(measurementSystem: MeasurementSystem) {
        self.measurementSystem = measurementSystem
    }

    func stringForValue(_ value: Double, axis: AxisBase?) -> String {

        let intValue = Int(value * 40)
        var suffixString = ""

        switch measurementSystem {
        case .US:
            suffixString =  "mph"
        case .Metric:
            suffixString = "km/h"
        }

        return "\(intValue)" + " " + suffixString
    }
}

class SpeedAndHRRightYAxisValueFormatter: IAxisValueFormatter {
    //right side is HR

    func stringForValue(_ value: Double, axis: AxisBase?) -> String {

        let intValue = Int(value * 210)

        return "\(intValue)" + " " + "bpm"
    }
}

您必须在 viewDidLoad() 方法中添加以下代码。这在我的一个项目中非常适合我。

override func viewDidLoad() {

    let leftYAxisValueFormatter = SpeedAndHRLeftYAxisValueFormatter(measurementSystem: measurementSystem)
    lineChartView.leftAxis.valueFormatter = leftYAxisValueFormatter
    lineChartView.leftAxis.labelTextColor = iPhoneThemeColor1

    let rightYAxisValueFormatter = SpeedAndHRRightYAxisValueFormatter()
    lineChartView.rightAxis.valueFormatter = rightYAxisValueFormatter
    lineChartView.rightAxis.labelTextColor = iPhoneThemeColor2
}

此外,更新 class 创建的代码如下:

@objc(LineChartFormatter)
class SpeedAndHRRightYAxisValueFormatter:NSObject, IAxisValueFormatter {
    ....
    //Your Code
    ....
}

@objc(LineChartFormatter)
class SpeedAndHRLeftYAxisValueFormatter:NSObject, IAxisValueFormatter {
    ....
    //Your Code
    ....
}

希望对您有所帮助。