Search code examples
ioschartsswift3pie-chart

danielgindi/Charts Pie Chart selected index


I am using Charts to draw a pie chart. It is working fine but i need to pass the selected portion index to next viewcontroller. I used below code and also read their release notes for Charts 3.0. I am working in Swift 3. In previous version the selected index was got from entry.dataSetIndex.

By this code i always get 0 index. Any help please.

extension ViewController: ChartViewDelegate {

    func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {

        print(highlight.dataSetIndex)
    }

}

Solution

  • Using iOS Charts 3.0.0, the following code outputs the selected index:

    class ChartController: UIViewController, ChartViewDelegate {
    
    func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
    
        if let dataSet = chartView.data?.dataSets[ highlight.dataSetIndex] {
    
            let sliceIndex: Int = dataSet.entryIndex( entry: entry)
            print( "Selected slice index: \( sliceIndex)")
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear( animated)
    
        // 1. create chart view
        let chart = PieChartView( frame: self.view.frame)
        chart.delegate = self
    
        // TODO: exercise for reader...add data, styles, etc.
    }