skip to Main Content

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


  1. Chosen as BEST ANSWER

    I found the solution.

     pieChart.widthAnchor.constraint(equalToConstant: 300),
     pieChart.heightAnchor.constraint(equalToConstant: 300)
    

    Add width and height solved the issue.


  2. When you set pieChart.translatesAutoresizingMaskIntoConstraints = false, pieChart.autoresizingMask = [.flexibleWidth, .flexibleHeight] will be useless. You need to set the constraints yourself, like:

    pieChart.widthAnchor.constraint(equalTo: view.widthAnchor)
    pieChart.heightAnchor.constraint(equalTo: view.heightAnchor)
    

    But based on your topAnchor & leadingAnchor, I guess you need trailingAnchor & bottomAnchor:

    NSLayoutConstraint.activate([
      pieChart.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 180),
      pieChart.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
      pieChart.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
      pieChart.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
    ])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search