(Swift) Charts give different values ​​different text colors

How to use Charts create beautiful charts in Swift

Our goal is to give different values different colors

First, create an empty ‘UIColor’ array called valueColors

    
...

override func viewDidLoad() {
super.viewDidLoad()

setChart(dataPoints: monthArray, values: temperatureArray)

}

func setChart(dataPoints: [String], values: [Double]) {

// 保存 colors
var valueColors = [UIColor]()

...

}

when we create every BarChartDataEntry, we can give one threshold, if threshold more than the assigned value, we will give the specified color otherwise it will be set to other colors

... 

override func viewDidLoad() {
super.viewDidLoad()

setChart(dataPoints: monthArray, values: temperatureArray)

}

func setChart(dataPoints: [String], values: [Double]) {

// 保存 colors
var valueColors = [UIColor]()

let threshold: Double = 20

// 產生 barChartEntry 每筆資料
for i in 0..<dataPoints.count {
dataEntry.append(BarChartDataEntry(x: Double(i), y: values[i]))
// 若溫度大於 20度,字體顏色就會設定為 黑色, 否則設為 紅色
if values[i] > threshold {
valueColors.append(.black)
}else {
valueColors.append(.red)
}

}
...

}

In this code, our threshold is 20. If the temperature is higher than the threshold, we specify black color; otherwise, we set red color.

Finally, we can use properties valueColors of BarChartDataSet class to set up our assigned colors

    override func viewDidLoad() {
super.viewDidLoad()

setChart(dataPoints: monthArray, values: temperatureArray)

}


func setChart(dataPoints: [String], values: [Double]) {

...
// 產生 barChartDataSet
let barChartDataSet = BarChartDataSet(entries: dataEntry, label: "test")
barChartDataSet.valueColors = valueColors

--

--