How to achieve trackball and access label above Bar on Bar charts in Swift 3x

允我心安 提交于 2019-11-28 00:28:58

Unfortunately, there is no way to set an image instead of a String or Double at the value above the bar. but yes we can access the value above bar please visit the mentioned link. https://github.com/danielgindi/Charts/issues/2126

class ViewController: UIViewController {
    var chartData = BarChartData()
    var months: [String]!
    var unitsSold = [Double]()
 weak var valueFormatter: IValueFormatter?
   @IBOutlet var viewForChart: BarChartView!
override func viewDidLoad() {
        super.viewDidLoad()
valueFormatter = self

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

 setChart(dataEntryX: months, dataEntryY: unitsSold)
}

    func setChart(dataEntryX forX:[String],dataEntryY forY: [Double]) {
        viewForChart.noDataText = "You need to provide data for the chart."
        var dataEntries:[BarChartDataEntry] = []
        for i in 0..<forX.count{

            let dataEntry = BarChartDataEntry(x: Double(i), y:  Double(forY[i]) , data: months as AnyObject?)
     dataEntries.append(dataEntry)
        }

        let chartDataSet = BarChartDataSet(values: dataEntries, label: "Units Sold")
       chartDataSet.setColor(UIColor.brown, alpha: 0.30)
        chartData = BarChartData(dataSet: chartDataSet)
chartData.barWidth = 0.75
        chartData.setDrawValues(true)
        viewForChart.data = chartData
viewForChart.xAxis.valueFormatter = IndexAxisValueFormatter(values: months)

        viewForChart.drawBordersEnabled = false

  viewForChart.data?.setValueFormatter(valueFormatter)
 }
}

add the extension above or beyond the class

extension ViewController: IValueFormatter {
    func stringForValue(_ value: Double, entry: ChartDataEntry, dataSetIndex: Int, viewPortHandler: ViewPortHandler?) -> String {
        print(value)
        //logic to print string at required point or value
        switch value {

        case 20.0: return "🙂"
        default: return ""
        }
    }
}

For swift 2x //add this to your class

class ValueFormator2:NSNumberFormatter{
    override func stringFromNumber(number: NSNumber) -> String? {
        print(number)
        switch number {
        case 3.0: return "🙂"

        default: return "\(number)"
        }
    }

}

and then

 func setChart(xValues: [String], yValuesLineChart: [Double], yValuesBarChart: [Double] , combinedChartView:CombinedChartView) {
    let form = ValueFormator2()
    combinedChartView.barData?.setValueFormatter(form)
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!