【发布时间】:2019-08-09 14:43:37
【问题描述】:
我想在饼图中提供自定义颜色(使用 Charts 窗格)。但是对于 setColors([NSUIColor]) 中的数组需要 NSUIColor 格式的颜色数组,我有颜色的十六进制代码。如何使用我的十六进制代码在饼图中实现自定义颜色?
我的代码功能:
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()
}
色码数组:
let TimeColorString = [UIColor.init(hex: "3366cc"),UIColor.init(hex: "ff9900"),UIColor.init(hex: "dc3912"),UIColor.init(hex: "109618")]
我用来将 Hexcode 转换为 UIColor 的扩展是:
//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
)
}
}
【问题讨论】:
-
什么是
NSUIColor?这是在哪里定义的? -
从错误中看来,
dataSet.setColors实际上需要一个UIColor实例而不是数组。但请在您的问题中包含setColors的函数签名。一些一般性建议:不要显式调用.init,使用简写语法UIColor(hex:)进行初始化。并且请遵守 Swift 命名约定,变量和函数是小写的。