2
votes

I am trying to fit a pie chart correctly to a view that is way taller than the chart. The problem is that I'd like to include a vertical list of legends at the bottom of the chart and this makes the heigh of the actual chart dynamic. If I have too many entries in the dataset one more more legend lines at the bottom of the chart not displayed.

Is there a practical way to get the "actual" or "rendered" height of the chart so that I can set pieChart.frame.height to this value ? Or otherwise, how can I adjust the height of the chart so that it includes everything including legend ?

enter image description here

@IBOutlet weak var pieChart: PieChartView!

var aDataEntry = PieChartDataEntry(value:30)
var bDataEntry = PieChartDataEntry(value:25)

var dataEntries = [PieChartDataEntry]()



override func viewDidLoad() {
    super.viewDidLoad()

    pieChart.chartDescription?.text = "A test"
    aDataEntry.label = "A"
    bDataEntry.label = "B"

    dataEntries = [aDataEntry, bDataEntry]

    updateChartData()

    // Do any additional setup after loading the view.
}

func updateChartData() {
    let chartDataSet = PieChartDataSet(values: dataEntries, label:nil)
    let chartData = PieChartData(dataSet: chartDataSet)
    var colours:[UIColor] = []
    for i in 1..<10 {
        colours.append(UIColor(named: "Colour" + String(i))!)
    }
    chartDataSet.colors = colours 
    pieChart.data = chartData
    pieChart.usePercentValuesEnabled = true
    pieChart.legend.orientation = .vertical
    pieChart.notifyDataSetChanged()
    print(pieChart.frame.height)
}
1

1 Answers

2
votes

After adding/settings the legends, you just need to call pieChartView.notifyDataSetChanged() otherwise, your legends will go out of the view. Here is the sample:

pieChartView.legend.verticalAlignment = .bottom
pieChartView.legend.horizontalAlignment = .center
pieChartView.legend.orientation    = .vertical
pieChartView.notifyDataSetChanged()

Edit 1: For a shortcut solution to your problem, use an empty string instead of nil when you call PieChartDataSet.

let chartDataSet = PieChartDataSet(values: dataEntries, label:"")