4

I can't figure out how to make a UILabel visible if a slice is selected in a Pie Chart View. I need to know how to identify if a slice was selected and then what slice was selected so I can put the right text in a UILabel and then unhide the label.

pseudocode:

if sliceSelected == true {

    var index = sliceSelected.index

    label.text = categoryArray[index]

    label.hidden = false

}
Max Phillips
  • 6,991
  • 9
  • 44
  • 71

4 Answers4

3

This is what worked for me. Attach an enum value as the data field of each entry, then analyze that value within the chartValueSelected delegate method.

For instance, if you have two slices, create the enum

internal enum SliceType {
    case pepperoni
    case cheese
}

Then when constructing the PieChartDataSet, construct your PieChartDataEntry objects with their SliceType as associated data:

let entry = PieChartDataEntry(value: pepperoniValue,
                              data: SliceType.pepperoni as AnyObject?)

Now make sure to set your view controller as the pie chart's delegate. Then in your chartValueSelected delegate method, do something like the following:

func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
    // Extract the SliceType from the selected value
    guard let sliceType = entry.data as? SliceType else {
        return
    }

    switch sliceType {
    case .pepperoni:
        // Configure the view for pepperoni being selected
    case .cheese:
        // Configure the view for cheese being selected
    }
}
Chris Chute
  • 3,229
  • 27
  • 18
2

Here's how you do it. Add ChartViewDelegate to your class and then insert the method below into the body of your code. Any thing that you want to happen if someone touches a value on your chart should go in the body of this function.

func chartValueSelected(chartView: ChartViewBase, entry: ChartDataEntry, dataSetIndex: Int, highlight: ChartHighlight) {

}

Shout out to this very useful tutorial for the ios-charts API: http://www.appcoda.com/ios-charts-api-tutorial/

Max Phillips
  • 6,991
  • 9
  • 44
  • 71
2

Each data separated by X axis of highlight. I can do it by doing this.

public func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
        pieChartView.highlightValues(nil)
        print(highlight.x)
        if highlight.x == 0.0 {

        } else if highlight.x == 1.0 {

        } else {

        }
    }
Firda Sahidi
  • 1,227
  • 1
  • 11
  • 22
0

Have you tried storing the selected slice in a variable like:

var slice: NSMutableDictionary = [:]

And then set the value for forKeyPath: index?

Joe
  • 157
  • 1
  • 12