Search code examples
swift3chartspie-chart

How to align a text in middle or center of PieChart In swift 3.0?


I want a text to be aligned into the center of piechart and also to fill the piechart border with specific colors according to the progress.

  • For PieChart, I am using VBPieChart Library.

I have attached my source code with screenshots.

func updateChartData()
    {
        let chart = PieChartView(frame: self.view.bounds)
        let track = ["Savings", "Offline-Online Rewards", "Refference Rewards"]
        let money = [650, 456.13, 78.67]
        var entries = [PieChartDataEntry]()
        for (index, value) in money.enumerated() {
            let entry = PieChartDataEntry()
            entry.y = value
            entry.label = track[index]
            entries.append( entry)
        }
        let set = PieChartDataSet( values: entries, label: "Pie Chart")
        var colors: [UIColor] = []
        for _ in 0..<money.count
        {
            let color1 = UIColor(rgb: 0x92C46B)
            let color2 = UIColor(rgb: 0x249DAC)
            let color3 = UIColor(rgb: 0x2A82C0)
            colors.append(color1)
            colors.append(color2)
            colors.append(color3)
        }
        set.colors = colors
        let data = PieChartData(dataSet: set)
        chart.data = data
        chart.noDataText = "No data available"
        chart.isUserInteractionEnabled = false
        let d = Description()
        d.text = "iOSCharts.io"
        chart.chartDescription = d
        self.view.addSubview(chart)

    }

Solution

  • In order to make the pie chart as you want in the second screenshot, there should be a center text.

    let chartAttribute = [ NSFontAttributeName: UIFont(name: "CustomFont", size: 14.0)! ]
    let chartAttrString = NSAttributedString(string: "3,000/-", attributes: chartAttribute)
    chart.centerAttributedText = chartAttrString
    

    In order to show decimal values in the pie chart,

    let data = PieChartData(dataSet: set)
    let format = NumberFormatter()
    format.numberStyle = .decimal
    format.decimalSeparator = "."
    let formatter = DefaultValueFormatter(formatter: format)
    data.setValueFormatter(formatter)
    chart.data = data