当前位置 : 主页 > 手机开发 > 其它 >

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

来源:互联网 收集:自由互联 发布时间:2021-06-11
我正在尝试使线图中的数据点标签显示自定义字符串而不是实际数字(使用iOS图表/图表库).我想知道是否有类似IAxisFormatter的东西我用来格式化我的x和y轴标签. 我想知道是否有人知道在
我正在尝试使线图中的数据点标签显示自定义字符串而不是实际数字(使用iOS图表/图表库).我想知道是否有类似IAxisFormatter的东西我用来格式化我的x和y轴标签.

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

您必须将IValueFormatter协议附加到ViewController并实现stringForValue(_:entry:dataSetIndex:viewPortHandler :)方法(1).

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

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)
    }
}
网友评论