Search code examples
iosswiftswift3ios10ios-charts

Add subtitle to center of pie-chart in swift


I want to display a subtitle below my main text in the center of the pie chart to let users know what the number represents. Is this possible? Right now I have a number that I converted to a string.

Below is my code:

func setCenter(days: Int){

    let circleColor = UIColor.black
    var textColor = UIColor.white

    pieChart.holeRadiusPercent = 0.3
    pieChart.transparentCircleRadiusPercent = 0.0
    let dayString = String(describing: days)
    let centerText = NSAttributedString(string: dayString , attributes: [
        NSForegroundColorAttributeName:textColor,NSFontAttributeName: UIFont(name: "SubwayLogo",size:30)!])
    pieChart.centerAttributedText = centerText
    pieChart.centerTextRadiusPercent = 1.0
    pieChart.holeColor = circleColor
} 

Let me know if you need to see other parts of the code. Thanks!


Solution

  • Nvm, I figured it out. You have to create 2 mutable attributed strings and then concatenate them with the second having a "\n"

    func setCenter(days: Int){
    
        let circleColor = UIColor.black
        let textColor = UIColor.white
    
        pieChart.holeRadiusPercent = 0.3
        pieChart.transparentCircleRadiusPercent = 0.0
        let dayString = String(describing: days)
        let centerText = NSMutableAttributedString()
        let numberText = NSMutableAttributedString(string: " " + dayString, attributes: [NSForegroundColorAttributeName:textColor,NSFontAttributeName: UIFont(name: "SubwayLogo",size:30)!])
        let descriptionText = NSMutableAttributedString(string: "\n Days Left", attributes: [NSForegroundColorAttributeName:textColor,NSFontAttributeName: UIFont(name: "SubwayLogo",size:8)!])
        centerText.append(numberText)
        centerText.append(descriptionText)
        pieChart.centerAttributedText = centerText
        pieChart.centerTextRadiusPercent = 1.0
        pieChart.holeColor = circleColor
    } 
    

    Make sure to play around with the spacing and sizes of the 2 mutable strings. I added an extra space before dayString to get it to align, pieChart is a little finicky.