I am trying to display pie chart programmatically but I am unable to do that.
here is the code.
// Create pie chart view
let pieChart: PieChartView = {
let pieChart = PieChartView()
pieChart.translatesAutoresizingMaskIntoConstraints = false
pieChart.autoresizingMask = [.flexibleWidth, .flexibleHeight]
return pieChart
}()
setPieChartData(chartView: pieChart, labels: labels, values: values)
setupViews() // Here I am adding the piechart view as follows
view.addSubview(pieChart)
NSLayoutConstraint.activate([
pieChart.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 180),
pieChart.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20)])
pieChart.setNeedsDisplay()
func setPieChartData(chartView: PieChartView, labels: [String], values: [Double]) {
var entries: [PieChartDataEntry] = []
for i in 0..<labels.count {
entries.append(PieChartDataEntry(value: values[i], label: labels[i]))
}
let dataSet = PieChartDataSet(entries: entries, label: "Pie Chart")
dataSet.colors = [.orange, .red]
// dataSet.drawValuesEnabled = true // Hide values on chart
//
// // Set additional properties for donut chart
// dataSet.drawIconsEnabled = true
// dataSet.drawValuesEnabled = true
// dataSet.sliceSpace = 2.0 // Adjust space between slices to create donut effect
let data = PieChartData(dataSet: dataSet)
chartView.data = data
}
What am I missing?
I tried adding background color and changed the constraints but it is not working.
2
Answers
I found the solution.
Add width and height solved the issue.
When you set
pieChart.translatesAutoresizingMaskIntoConstraints = false
,pieChart.autoresizingMask = [.flexibleWidth, .flexibleHeight]
will be useless. You need to set the constraints yourself, like:But based on your
topAnchor
&leadingAnchor
, I guess you needtrailingAnchor
&bottomAnchor
: