Mr. JD Agrawal
Mr. JD Agrawal

Reputation: 144

Cannot convert value of type '[UIColor]' to expected argument type 'NSUIColor' (aka 'UIColor')

I want to give custom color in a Pie Chart(using the Charts pod). But for that the array in setColors([NSUIColor]) requires an array of colors in NSUIColor format and I have the hexcode for the colors. How can I implement custom color in the Pie Chart using my hexcode?

My code function:

func pieChartUpdate ()
{
    //future home of pie chart code

    let entry1 = PieChartDataEntry(value: Double(10), label: "Morning")
    let entry2 = PieChartDataEntry(value: Double(20), label: "Evening")
    let entry3 = PieChartDataEntry(value: Double(30), label: "Midday")
    let entry4 = PieChartDataEntry(value: Double(40), label: "Before Bed")
    let dataSet = PieChartDataSet(values: [entry1, entry2, entry3, entry4], label: "Widget Types")
    let data = PieChartData(dataSet: dataSet)
    pieChartTime.data = data
    pieChartTime.chartDescription?.text = "Share of Widgets by Type"

    //All other additions to this function will go here

    dataSet.setColors(TimeColorString)
    dataSet.valueColors = [UIColor.black]


    //This must stay at end of function
    pieChartTime.notifyDataSetChanged()

}

Array of color code:

let TimeColorString = [UIColor.init(hex: "3366cc"),UIColor.init(hex: "ff9900"),UIColor.init(hex: "dc3912"),UIColor.init(hex: "109618")]

And extension I'm using to convert Hexcode into UIColor is:

//To convert hexcode into UI Color
extension UIColor {
convenience init(hex: String) {
    let scanner = Scanner(string: hex)
    scanner.scanLocation = 0

    var rgbValue: UInt64 = 0

    scanner.scanHexInt64(&rgbValue)

    let r = (rgbValue & 0xff0000) >> 16
    let g = (rgbValue & 0xff00) >> 8
    let b = rgbValue & 0xff

    self.init(
        red: CGFloat(r) / 0xff,
        green: CGFloat(g) / 0xff,
        blue: CGFloat(b) / 0xff, alpha: 1
    )
    }
}

Upvotes: 2

Views: 8010

Answers (2)

Ali Raza
Ali Raza

Reputation: 384

First Create array of NSUIColor and then use it like below:

let TimeColorString = [NSUIColor(cgColor: UIColor(hex: "#00a8e1").cgColor)]
dataSet.colors = TimeColorString

Upvotes: 4

Vini App
Vini App

Reputation: 7485

Set the colors like below :

dataSet.colors = TimeColorString

If you want to use setColors, below are the functions from Charts :

open func setColors(_ colors: [NSUIColor], alpha: CGFloat)

open func setColors(_ colors: NSUIColor...)

How to use :

dataSet.setColors(TimeColorString, alpha: 1.0)

Upvotes: 3

Related Questions