swiftswiftcharts

How to set center view label in piechart Swift?


I want a group label to be aligned into the center of screen and also to fill the border with specific colors according to the view contain group lable.

For PieChart, I am using Chart Library. I have attached my source code with screenshots.

let pieChart = PieChartView(frame: CGRect(x: 0, y:0, width: 20, height: 170))
pieChart.backgroundColor = Color.backgroundwhite
//pieChart.chartDescription?.text = "Tong quan tai khoan"
pieChart.translatesAutoresizingMaskIntoConstraints = false
//pieChart.noDataText = "No date to display"
pieChart.rotationEnabled = false
pieChart.transparentCircleRadiusPercent = 0
pieChart.drawEntryLabelsEnabled = false
// view.addSubview(pieChart)
 //       pieChart.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0).isActive = true
  //     pieChart.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: -220).isActive = true
//        pieChart.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 1).isActive = true
//        pieChart.heightAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.4).isActive = true
//get sumdata

for i in 0..<self.FundBM.count {
    self.sumBALQTTY = self.sumBALQTTY + (self.FundBM[i].BALQTTY! as NSString).doubleValue
}
//fill chart
var dataEntries: [ChartDataEntry] = []
for i in 0..<self.FundBM.count {
    self.percent = ((self.FundBM[i].BALQTTY! as NSString).doubleValue/self.sumBALQTTY)*100
    let dataEntry = PieChartDataEntry(value: self.percent, label: self.FundBM[i].SYMBOL!.replacingOccurrences(of: "VFM", with: ""))
    dataEntries.append(dataEntry)

}
let chartDataSet = PieChartDataSet(values: dataEntries, label: "")
chartDataSet.valueFont = UIFont.systemFont(ofSize: 6)
var  colors: [UIColor] = []
var colorsRoot : [UIColor] = [
    UIColor("#e57c24"),
    UIColor("#de1f26"),
    UIColor("#190b0d"),
    UIColor("#039cd0"),
    UIColor("#0f3c60"),
    UIColor("#979798")
]
for i in 0..<dataEntries.count {
    colors.append(colorsRoot[i])
}
chartDataSet.colors = colors
//chartDataSet.colors = ChartColorTemplates.material()
chartDataSet.sliceSpace = 0
chartDataSet.selectionShift = 1
let chartData = PieChartData(dataSet: chartDataSet)
let formatter = NumberFormatter()
formatter.numberStyle = .percent
formatter.maximumFractionDigits = 2
formatter.multiplier = 1.0
formatter.percentSymbol = "%"
formatter.zeroSymbol = ""
chartData.setValueFormatter(DefaultValueFormatter(formatter: formatter))
pieChart.data = chartData
return pieChart

enter image description here


Solution

  • You can set this using legend as below,

    let legend = pieChart.legend
    legend.horizontalAlignment = .center
    legend.verticalAlignment = .bottom
    legend.orientation = .horizontal