如何在 iOS 图表中自定义数据点标签?

2024-03-12

我试图使折线图中的数据点标签显示自定义字符串而不是实际数字(使用 iOS 图表/图表库)。我想知道是否有类似 IAxisFormatter 的东西,我用它来格式化我的 x 和 y 轴标签。

我想知道是否有人知道如何在 Swift 中准确地做到这一点?我似乎无法在网上找到任何示例。谢谢!


你必须附加IValueFormatter协议到你的 ViewController 并实现stringForValue(_:entry:dataSetIndex:viewPortHandler:)方法(1)。

然后将 ViewController 设置为图表数据集的 valueFormatter 委托 (2)。

import UIKit
import Charts

class ViewController: UIViewController, IValueFormatter {

    @IBOutlet weak var lineChartView: LineChartView!

    // Some data
    let months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    let unitsSold = [20.0, 4.0, 3.0, 6.0, 12.0, 16.0, 4.0, 18.0, 2.0, 4.0, 5.0, 4.0]

    // (1) Implementation the delegate method for changing data point labels. 
    func stringForValue(_ value: Double,
                        entry: ChartDataEntry,
                        dataSetIndex: Int,
                        implement delegate methodviewPortHandler: ViewPortHandler?) -> String{

        return "My cool label " + String(value)
    }

    func setChart(dataPoints: [String], values: [Double]){
        var dataEntries: [ChartDataEntry] = []

        // Prepare data for chart
        for i in 0..<dataPoints.count {
            let dataEntry = ChartDataEntry(x: Double(i), y: values[i])
            dataEntries.append(dataEntry)
        }

        let lineChartDataSet = LineChartDataSet(values: dataEntries, label: "Units Sold")
        let lineChartData = LineChartData(dataSets: [lineChartDataSet])

        // (2) Set delegate for formatting datapoint labels
        lineChartData.dataSets[0].valueFormatter = self

        lineChartView.data = lineChartData
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        setChart(dataPoints: months, values: unitsSold)
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 iOS 图表中自定义数据点标签? 的相关文章

随机推荐